[英]how to control input data format (C)?
有誰知道一種有效的方法來檢查掃描數據的格式?
例如,如果我嘗試讀取一個整數並輸入一個字符,您將如何告訴該程序不正確?
您可以檢查scanf()
成功,它返回執行的成功轉換次數。
在依賴結果之前,您應始終進行檢查,因為如果失敗,則變量可能包含未定義的數據(如果被引用則導致未定義的結果)。
您可以使用if
檢查,並在失敗時使用其他轉換說明重試:
if(scanf("%d", &x) == 1)
printf("got integer %d\n", x);
else if(scanf("%c", &y) == 1)
printf("got character '%c'\n", y);
else /* more attempts */
當然,如果存在“子匹配項”,則會變得很麻煩,因此順序很重要。 這也是更好的方式來輸入處理分為兩個步驟,以上:
fgets()
讀取整行輸入 sscanf()
解析行 這樣,您可以避免由於輸入流而導致的問題:
char line[128];
if(fgets(line, sizeof line, stdin) != NULL)
{
int x;
char y;
if(sscanf(line, "%d", &x) == 1)
printf("got integer %d\n", x);
else if(sscanf(line, "%c", &y) == 1)
printf("got character '%c'\n", y);
}
請注意,如果要同時掃描整數和浮點數,由於典型的浮點數(例如"3.1416"
)以合法的整數開頭,因此它仍然很麻煩。 對於這些情況,您可以使用strtoXXX()
函數系列,該函數系列讓您在轉換后檢查其余部分。
正如您在問題中提到的那樣,您只在玩數字和字符,這是一個非常簡單的解決方案,如下所示
//while reading a char
scanf("%c",&temp);
if(!((temp >= 65 && temp <= 90) || (temp >= 97 && temp <= 122)))
printf("Only characters are allowed!\n");
希望這可以幫助!
scanf("%s", &c);
if(!atoi(c)) puts("You have entered a character");
if(atoi(c) != 0) puts("You have entered an integer");
Scanner sc = new Scanner (System.in);
try {
// assume that the input from the user is not an integer,
// in that case the program cannot convert the input (which is a String) into
// an integer. Because of this situation it'll jump to the 'catch' part of the
// program and execute the code.
int input = Integer.valueOf(sc.nextInt);
// if the input is an integer lines below the above code will be executed.
// Ex. "int x = ( input + 10 ) "
}
catch (Exception ex) {
System.out.println("Invalid input, please retry!");
// if you want to get more information about
// the error use the 'ex' object as follows.
System.out.println(ex);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.