C 编程 - 循环直到用户输入数字 scanf [英] C programming - Loop until user inputs number scanf
问题描述
我需要有关程序错误检查的帮助.我要求用户输入一个整数,我想检查用户输入是否为整数.如果没有,请重复扫描.
I need help with error checking for my program. I'm asking the user to input a integer and I would like to check if the users input is a integer. If not, repeat the 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
",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!
");
}else {
printf("The sum of these two integers is not a multiple of 3...
");
}
return 0;
}
推荐答案
scanf
根据您的格式返回已成功读取的项目数.您可以设置一个循环,仅当 scanf("%d", &number2);
返回 1
时才退出.然而,诀窍是当 scanf
返回零时忽略无效数据,因此代码如下所示:
scanf
returns the count of items that it has successfully read according to your format. You can set up a loop that exits only when scanf("%d", &number2);
returns 1
. The trick, however, is to ignore invalid data when scanf
returns zero, so the code would look like this:
while (scanf("%d",&number2) != 1) {
// Tell the user that the entry was invalid
printf("You did not enter a valid number
");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}
由于您在代码中多次读取一个数字,请考虑创建一个函数来隐藏此循环,并在您的 main
中调用此函数两次以避免重复.
Since you read a number more than once in your code, consider making a function to hide this loop, and call this function twice in your main
to avoid duplication.
这篇关于C 编程 - 循环直到用户输入数字 scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!