C语言编程 - 循环,直到用户输入号码scanf函数 [英] C programming - Loop until user inputs number scanf
问题描述
我需要我的程序错误检查帮助。我要求用户输入一个整数,我想检查,如果用户输入的是一个整数。如果没有,重复scanf函数。
我的code:
INT主要(无效){ INT数字1,数字;
INT总和; //要求用户整数加
的printf(请输入第一个整数的补充。);
scanf函数(%d个,&安培;数量1); 的printf(请输入第二个整数补充。);
scanf函数(%d个,&安培;数字2);
//添加整数
总和=数字1 +数字2; //打印总和
的printf(,数字1,数字,总和%D和%D =%d个\\ n之和); //检查是否总和divisable 3
如果(总和%3 == 0){
的printf(这两个整数的和是3的倍数\\ n!);
}其他{
的printf(这两个整数的和是不是3的倍数... \\ n);
}
返回0;
}
scanf函数
返回它已按照您的格式读取成功的项目数。您可以设置一个循环退出只有当 scanf函数(%d个,&安培;数字2);
收益 1
。这一招,但是,忽略无效数据时 scanf函数
返回零,所以code是这样的:
而(scanf函数(%d个,&安培;!号码2)= 1){
//告诉该条目是无效的用户
的printf(你没有输入有效的数字\\ n);
//星号*告诉scanf函数读取和忽略的价值
scanf函数(%* S);
}
由于您为code读取数超过一次,考虑一个函数来隐藏这个循环,并在主
,以避免两次调用这个函数重复。
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.
My code:
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
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\n");
// Asterisk * tells scanf to read and ignore the value
scanf("%*s");
}
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屋!