2012-12-06 189 views
1

我試圖做一個while循環,其中條件檢查字符串的前四個元素不是整數。這是我的代碼,它不起作用。我嘗試使用ctype.h頭中的isdigit函數。如何檢查輸入字符串是否包含整數

char tr_code[200]; 
char *endptr; 

scanf("%s", &tr_code); 
fd_code=strtol(tr_code,&endptr,10); 

while(strlen(tr_code)!=4 && isdigit(tr_code[0])==0 && isdigit(tr_code[1])==0 && isdigit(tr_code[2])==0 && isdigit(tr_code[3])==0) 
{ 
    printf("\nInvalid Code. please enter another '4-digit' Code: "); 
    scanf("%s", &tr_code); 
    fd_code=strtol(tr_code,&endptr,10); 
} 
+0

它不起作用?有什麼症狀? –

+0

它以什麼方式不起作用?你期望什麼,以及發生了什麼? – Ryan

+0

它剛剛退出循環 –

回答

0

IIRC'scanf'簽名返回一個整數,它是在終端讀取的字符數。

2

您使用&&,但||是你應該用什麼:

while(strlen(tr_code) != 4 || !isdigit(tr_code[0]) || !isdigit(tr_code[1]) || !isdigit(tr_code[2]) || !isdigit(tr_code[3])) 

隨着&&,這四個字符長的任何輸入,或在任何前四個位置的數字(即使該內存是來自上次輸入的剩餘物,因爲字符串可能更短)將通過。

+0

之後需要字符串變量哦,謝謝。有用。 :) –

相關問題