2016-03-15 62 views
0

我剛剛完成(相當成功)在計算機科學一和二在一個領先的NCAA Division 1大學介紹了專門用C++教的,我不能告訴你有多少次我搜索這個網站如何接受和驗證一個int一個int,一個字符,只有一個字符,一個字符串,只有一個字符串?毫無疑問,對於這些問題有很多方法,但通常情況下SO的具體情況非常特殊。我只是在尋找一種按照上面的要求工作的通用方法。我提供我的方法,我自己制定了。我無法想象沒有其他類似的位置確實存在相同的問題。如果還有其他方法可以完成a)工作的這些看起來較小的任務,並且b)涉及的編碼比我所概述的要少,那麼我會很樂意看到它。int,char和string cin和驗證方法?

+0

這看起來太寬泛了。有一百萬種方法可以做到這一點。 – yellowantphil

回答

0
#include <string> 
#include<iostream> 
using std::cin; 
using std::cout; 

int main() { 

    int answer1 = 0; 
    cout << "An int Question?\n" 
     << "1. Yes.\n" 
     << "2. No.\n"; 
    while (!(cin >> answer1) || answer1 < 1 || answer1 > 2) { 
    cin.clear(); 
    cin.ignore(std::numeric_limits<std::stream_size>::max(), '\n'); 
    cout << "Input Error!\n" 
      << "An int Question?\n" 
      << "1. Yes.\n" 
      << "2. No!\n"; 
    } 
    cout << "The int answer is " << answer1 << "\n\n"; 


char answer2 = 'X'; 
cout << "A char Question?\n" 
     << "A. Yes.\n" 
     << "B. No.\n"; 
while (!(cin >> answer2) || !isalpha(answer2) || answer2 != 'A' && answer2 != 'B') { 
    cin.clear(); 
    cin.ignore(std::numeric_limits<std::stream_size>::max(), '\n'); 
    cout << "Input Error!\n" 
      << "A char Question?\n" 
      << "A. Yes.\n" 
      << "B. No!\n"; 
    } 
    cout << "The char answer is " << answer2 << "\n\n"; 


    std::string answer3 = ""; 
    cout << "A string Question?\n" 
     << "Yes.\n" 
     << "No.\n"; 
    while (!(cin >> answer3) || answer3 != "Yes" && answer3 != "No") { 
    cin.clear(); 
    cin.ignore(std::numeric_limits<std::stream_size>::max(), '\n'); 
    cout << "Input Error!\n" 
      << "A string Question?\n" 
      << "Yes.\n" 
      << "No.\n"; 
    } 
    cout << "The string answer is " << answer3 << "\n\n"; 
} 
+0

爲什麼使用256來調用'ignore'?你應該使用'std :: numeric_limits :: max()' – NathanOliver

+0

@Nathan:謝謝,你是對的,除此之外,我通常只關注那些更新的C++,並且增加了一些複雜。 – Chris

+0

答案應該是給大家的。如果增加了一個額外的東西,它可能不得不查找,如果它使代碼更脆弱? – NathanOliver