2011-12-28 54 views
-1

我想驗證用戶輸入。下面的代碼:驗證用戶輸入 - Objective-C

do{ 
     NSLog(@"Please select from the following options: D/ W/ T/ Q"); 
     res = scanf("%c", &s1); 

     if(res ==0) { 
      NSLog(@"Invalid entry."); 
     } 
    }while (res ==0); 

我想提高上面的代碼,使得它不會允許用戶輸入任何東西(如一個數字,一個字符串,或任何負數),但只有一個單個字符(以具體而言,只有提示中給出的一個選項)。

當前的代碼沒有這樣做。

+0

簽名被刪除,請參閱FAQ。 – 2011-12-28 07:18:19

+0

@Sameera:當您移除簽名的其餘部分時,隨意刪除「謝謝」部分。 – 2011-12-28 08:09:56

回答

1
boolean bValid = true; 
    do { 
     NSLog(@"Please select from the following options: D/ W/ T/ Q"); 
     res = scanf("%c", &s1); 

     if(res == 'D' || res == 'W' || res == 'T' || res == 'Q'){ 
      bValid = false; 
     } 
     else{ 
      //Error message 
     } 
    } while (bValid == true); 

您可以使用此代碼。 只需檢查出來。

+0

謝謝 - 這是完美的。 – Renu 2011-12-31 07:17:12

1

那麼一個選擇是首先讀取鍵盤作爲字符串

char buffer[128]; 
fgets(buffer, sizeof(buffer), stdin); 

一旦你的線,然後檢查是否選擇之一,似乎只有第一個字母是你的情況顯著:

switch(toupper(buffer[0])) 
{ 
    case 'D': {...} ; // do whatever u need to do 
    case 'W': {...} ; 
    case 'T': {...} ; 
    case 'Q': {...} ; 
    default: {...} ; 
}