2012-10-11 45 views
1

enter image description here我需要限制用戶在輸入字符時輸入一個整數和字符串。我有一個整數的方法,我只需要適應它的字符。誰能幫我這個。Validator for one char for user input

char getChar() 
    { 
     char myChar; 
     std::cout << "Enter a single char: "; 
     while (!(std::cin >> myChar)) 
     { 
      // reset the status of the stream 
      std::cin.clear(); 
      // ignore remaining characters in the stream 
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
      // ^^^ This line needs to be changed. 
      std::cout << 

      "Enter an *CHAR*: "; 
    } 
    std::cout << "You entered: " << myChar << std::endl; 
    return myChar; 
} 

char getChar() 
{ 
    char myChar; 
    std::cout << "Enter an Char: "; 
    while (!(cin >> myChar)) 
    { 
     // reset the status of the stream 
     cin.clear(); 
     // ignore remaining characters in the stream 
     cin.ignore(std::numeric_limits<char>::max() << '\n'); 
     cout << "Enter an *CHAR*: "; 
    } 
    std::cout << "You entered: " << myChar << std::endl; 
    return myChar; 
} 

我試過這個,沒有錯誤。但它並沒有發生。

+0

我想不出一種'cin >> myChar'可能因非法轉換而失敗的方式(例如''0'是一個合法的'char')。讀取後您需要檢查'myChar'的值。 – hmjd

回答

0

我改變了methid這樣:

char getChar(string q) 
{ 
char input; 
do 
{ 
cout << q.c_str() << endl; 
cin >> input; 
} 
while(!isalpha(input)); 
return input; 
} 

在我主我有:

字符串輸入= 「?你的性別M/F」; char sex = getChar(input); cout < <性別< <「\ n」;

Doin this,我不允許輸入一個數字問問什麼是性別。

3

我猜你的「不工作」,你的意思是,即使你輸入一個更長的字符串或數字,它仍然被接受。這是因爲通過<<運算符輸入的所有字母和數字仍然是單個字符。

你必須添加其他檢查,如果你不希望非字母字符:

while (!(std::cin >> myChar) || !std::isalpha(mychar)) 

std::isalpha的說明,請參見this reference

+0

你的猜測是正確的,在方法中我會把額外的支票? – Pendo826

+0

@ Pendo826將'while'循環更改爲答案中的那個循環。 –

+0

哦,我明白了。我現在只是測試這個代碼:)。 – Pendo826