我正在尝试使用C中的一个代码,我需要检查用户输入的值是否为整数。我试过isdigit()但它没有用。我希望你们有任何帮助。
while(1) {
printf( " \n -------------Enter your choice --------------------------\n ");
printf("\n 1. Insertion \n 2. Preorder \n 3. Inorder \n 4. Postorder \n 5. Deletion \n 6. Search \n 7. Exit \n ");
scanf ("%d", &save_the_input );
switch(save_the_input) {
case 1 :
printf( " \n......... Please enter the numbers to create the binary tree....... \n");
scanf ("%d", &number_of_nodes);
printf( "\n...... Please enter the numbers one by one... \n");
for (iterator = 0; iterator < number_of_nodes; iterator++) {
scanf ("%d", &user_input);
if (( user_input < 0 )) {
printf( " ------- You have either entered a Character or a Negative number ----- \n ");
printf( " ------- Please enter the Positive integer values-------------\n ");
main();
}
else {
root_node = insert (root_node, user_input);
printf("\n");
printf("data element inserted is %d \n ", user_input);
}
}
break;
答案 0 :(得分:1)
您可以使用sscanf
int num;
ret = sscanf(line,"%d",&num);
if (ret == 1) {
// num contains number
} else {
// not a number
}
答案 1 :(得分:0)
for (i = 0; i < strlen(s); ++i)
{
if (!isdigit(s[i]))
{
return false;
}
return true;
}