C编程 – 循环直到用户输入数字scanf

我需要帮助我的程序错误检查。 我要求用户输入一个整数,我想检查用户输入是否为整数。 如果没有,请重复scanf。

我的代码:

int main(void){ int number1, number2; int sum; //asks user for integers to add printf("Please enter the first integer to add."); scanf("%d",&number1); printf("Please enter the second integer to add."); scanf("%d",&number2); //adds integers sum = number1 + number2; //prints sum printf("Sum of %d and %d = %d \n",number1, number2, sum); //checks if sum is divisable by 3 if(sum%3 == 0){ printf("The sum of these two integers is a multiple of 3!\n"); }else { printf("The sum of these two integers is not a multiple of 3...\n"); } return 0; } 

scanf根据您的格式返回已成功读取的项目数。 您可以设置一个仅在scanf("%d", &number2);时退出的循环scanf("%d", &number2); 返回1 。 但是,技巧是当scanf返回零时忽略无效数据,因此代码如下所示:

 while (scanf("%d",&number2) != 1) { // Tell the user that the entry was invalid printf("You did not enter a valid number\n"); // Asterisk * tells scanf to read and ignore the value scanf("%*s"); } 

由于您在代码中多次读取数字,因此请考虑使用函数隐藏此循环,并在main函数中调用此函数两次以避免重复。

这是您的问题的解决方案。 我刚刚修改了一些代码。 阅读任何解释的评论。

 #include #include //included to use atoi() #include //included to use isalpha() #define LEN 3 //for two digit numbers int main(void) { char *num1=malloc(LEN); char *num2=malloc(LEN); int i,flag=0; int number1,number2; int sum; do { printf("Please enter the first integer to add = "); scanf("%s",num1); for (i=0; i 

我只为两位数设计了这个数字,但对于我而言,它对两位数以上的数字工作正常。 请告诉我你的情况也是如此。
如果你发现为什么会这样,请评论。

你也可以使用strtol()而不是atoi() 。 由于价值较小,我没有使用它。

atoi()strtol()之间的区别

atoi()
亲:简单。
Pro:转换为int
Pro:在C标准库中。
亲:快。
Con:没有error handling。
Con:既不处理hex也不处理八进制。

strtol()
亲:简单。
Pro:在C标准库中。
亲:良好的error handling。
亲:快。
Con:转换为long ,而不是int ,其大小可能不同。

我想说你必须做一些自定义validation来检查scanf是否读取整数。我使用的是对scanf不感兴趣的fgets

 #include  #include  #include  #include  int validate ( char *a ) { unsigned x; for ( x = 0; x < strlen ( a ); x++ ) if ( !isdigit ( a[x] ) ) return 1; return 0; } int main ( void ) { int i; char buffer[BUFSIZ]; printf ( "Enter a number: " ); if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) { buffer[strlen ( buffer ) - 1] = '\0'; if ( validate ( buffer ) == 0 ) { i = atoi ( buffer ); printf ( "%d\n", i ); } else printf ( "Error: Input validation\n" ); } else printf ( "Error reading input\n" ); return 0; } 

解决这个问题的方法很简单

  1. 使用fgets()stdin读取。

  2. 使用strtol()将值转换并存储到int 。 然后检查char **endptr以确定转换是否成功[指示整数]。

  3. 执行剩余任务。