如何强制用户输入正整数?

Taz*_* B. 4 c command-line

强制用户输入正整数并将用户置于循环中直到它们为止.

所以我希望包括不允许超过0的字符在内的所有内容

我尝试了以下方法:

while (i < 0) do { 
    printf("please input a number that's positive"); 
    scanf("%d", i); 
}
Run Code Online (Sandbox Code Playgroud)

Sid*_*qui 9

对于正整数,请使用以下代码

int i;
do 
{ 
  printf("please input a number that's positive"); 
  scanf("%d", &i); 
}while (i < 0); 
Run Code Online (Sandbox Code Playgroud)

c语言不提供用户输入的错误检查.期望用户输入正确的数据类型.例如,如果用户在预期整数值时输入了字符,则程序可能会进入无限循环或异常中止.

  • 您还必须检查`scanf()`的返回值,以确保它实际上可以解释输入的十进制整数.如果它返回"0",那么你必须从无法读取为数字的字符中清除`stdin`. (3认同)