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

Asi*_* x3 5 c if-statement 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;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 8

scanf根据您的格式返回已成功读取的项目数.您可以设置仅在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");
}
Run Code Online (Sandbox Code Playgroud)

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