我编写了这段代码,所有要做的就是输入整数,直到输入否定为止:
int result = 0, input_number = 0;
while(input_number >= 0){
printf("Please enter students IDs(negetive to stop)= ");
result = scanf("%d", &input_number);
if(result != 1){
printf("Invalid input! try again...\n");
continue;
}
}
当输入为int-一切正常时,
但是当输入一个char(任何char不是int)时,
循环变得无穷无尽,scanf不再请求任何输入。
不建议我使用替换扫描,因为它是学校的工作, 必须使用scanf。
输入char输出后:
Please enter students IDs(negetive to stop)= 4
Please enter students IDs(negetive to stop)= 5
Please enter students IDs(negetive to stop)= r
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
Please enter students IDs(negetive to stop)= Invalid input! try again...
...
答案 0 :(得分:0)
读取字符串,%s是格式说明符,然后在代码中转换为int。 atoi()(或strtol(),如果你是C ++)将工作。