例如,你可以改變它如下。
#include <stdio.h>
#define doSomethingElse(input) do{ printf("your input is %d\n", input); }while(0)
int main(void){
int input;
int status;
while ((status = scanf("%d", &input)) != EOF) {
if (status == 0) {
printf("Not a number\n");
while(getchar() != '\n'); //clear input
}
else {
doSomethingElse(input);
}
}
}
但是,這不能檢查輸入如123.456
。 (接受123
)
所以,建議用fgets
輸入並用strtol
查詢。
前面已經指出的那樣,像scanf(" %s %d", string, &input)
數量後不能檢查輸入。
所以,爲了方便,請檢查後向輸入。
char string[32], ch;
int input;
int status;
while ((status = scanf("%31s %d%c", string, &input, &ch)) != EOF) {
if (status == 3 && ch == '\n') {
doSomethingElse(input);
}
else {
printf("Not a number\n");
while(getchar() != '\n'); //clear input
}
}
使用
fgets
和
strtol
實施例(mystrtoi
了重組chux的answer。感謝)
#include <stdio.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#define doSomethingElse(input) do{ printf("your input is %d\n", input); }while(0)
int mystrtoi(const char *str, int *err) {
char *endptr;
*err = errno = 0;
long l = strtol(str, &endptr, 0);
if (errno == ERANGE || *endptr != '\0' || str == endptr) {
*err = 1;
}
// Only needed if sizeof(int) < sizeof(long)
if (l < INT_MIN || l > INT_MAX) {
*err = 1;
}
return (int) l;
}
int main(void){
char line[128];
char string1[32], string2[128];
int num, err;
while (fgets(line, sizeof line, stdin)){
// if(2 != sscanf(line, "%31s %31s", string1, string2)){// or use strtok to split
if(2 != sscanf(line, "%31s %127[^\n]", string1, string2)){
printf("invalid input\n");
continue;
}
num = mystrtoi(string2, &err);
if(err) {
printf("Not a number\n");
}
else {
doSomethingElse(num);
}
}
}
我認爲'isNotANumber(輸入)'不能在循環檢查'input' 。 – BLUEPIXY
由於'input'被定義爲'int',所以它的值將永遠是一個整數,至少與'scanf()'沒有失敗一樣長。 – alk
如果您不知道輸入是數字,則不能使用scanf。 (或者,你可以使用scanf,但是如果scanf沒有讀取輸入,因爲它不是一個數字,那麼你將不得不以其他方式讀取它,所以scanf毫無意義。)需要以其他方式輸入數據。嘗試'fread',然後使用'strtol'檢查它是否是一個整數。順便說一句,你的意思是「數字」,還是「整數」?準確。 –