當輸入不滿足第一個if語句的條件時,不是理想的重新給type1和type2賦值而是死循環(huán)。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
//6.5.1
long int type1, type2, flag=0;
printf("請輸入要測試的兩個整數(shù):");
while (flag==0) {
scanf("%li %li", &type1, &type2);
if( (type1 ==(long int) type1) && (type2 ==(long int) type2) && type2 != 0){
if( type1 % type2 == 0 ){
printf("%li可以被%li整除", type1, type2);
flag=1;
}else{
printf("%li不可以被%li整除", type1, type2);
flag=1;
}
}else{
printf("只能輸入整數(shù),并且第二個數(shù)不能為0,請重新輸入:");
}
}
return 0;
}
}
人生最曼妙的風(fēng)景,竟是內(nèi)心的淡定與從容!
You need to judge the return value of scanf to see if there is illegal input. If there is illegal input, you must first clear the previously entered content, for example, use this code:
if (scanf("%li %li", &type1, &type2) != 2) { // illegal input
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
// intend to be blank
}
}
Of course, it is generally believed that scanf
不太安全,因此至少都應(yīng)該用fgets
以及sscanf
Rewritten:
char buffer[256];
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
// error or no more to read
// ...
}
if (sscanf(buffer, "%li %li", &type1, &type2) != 2) { // illegal input
// print error message
// continue
// ...
}
PS. (type1 ==(long int) type1) && (type2 ==(long int) type2)
This sentence is quite redundant.
This is a C problem not an Objective-c problem.
If scanf encounters illegal input, it will fail to execute, but the illegal input will still remain in the buffer. When scanf requests input again, it will directly read the buffer without waiting for terminal input.
The solution has been given by Theo.