2010-10-31 103 views
1

我正在製作一個使用if else語句的小程序,但不是使用數字來控制流程,而是希望能夠使控制工作與是和否;使用用戶輸入如YES和NO來控制C++中的程序流程

例如:

cout << "would you like to continue?" << endl; 
cout << "\nYES or NO" << endl; 
int input =0; 
cin >> input; 
string Yes = "YES"; 
string No = "NO"; 

if (input == no) 
{ 
    cout << "testone" << endl; 
} 
if (input == yes) 
{ 
    cout << "test two" << endl; 
     //the rest of the program goes here i guess? 
} 
else 
{ 
    cout << "you entered the wrong thing, start again" << endl; 
       //maybe some type of loop structure to go back 
} 

,但我似乎無法得到這部分的任何變化的工作,我可以讓用戶輸入一個0或1,而不是,但似乎真的愚蠢,我寧願它儘可能的自然,用戶不會說數字嗎?

也是我需要能夠簡單地添加更多的單詞,例如「不,不,野應否N」一切就一定意味着沒有

希望這有一定道理

也是我很想使用一個窗口,但我只學到了基本的C++到目前爲止,甚至沒有,我無法找到任何有關基本Windows編程的好資源。

+2

這不是Windows編程。這只是標準的,獨立於平臺的C++。我建議你閱讀任何初學C++的書,而不要去看Windows編程教程。 – 2010-10-31 11:53:27

回答

4

您沒有閱讀string,您正在閱讀int

嘗試這樣的:

string input; 

代替

int input = 0; 

此外,C++是區分大小寫的,所以你不能定義一個名爲Yes變量,然後嘗試用它作爲yes。他們需要處於同一個案例中。

btw,你的第二個if聲明應該是else if,否則如果你輸入「NO」,那麼它仍然會進入最後的else塊。

所有的
+1

字符串輸入;就足夠了,不需要初始化它。 – Nikko 2010-10-31 11:55:33

+0

所以現在它接受否或是,但運行else語句 – Joseph 2010-10-31 11:56:38

+0

謝謝,如果在中間添加了其他的, – Joseph 2010-10-31 12:03:32

0
string input; 
cin >> input; 
if (input == "yes"){ 

} 
else if (input == "no"{ 

} 

else { 
    //blah 
} 
2

首先,input必須std::string,不int

而且,你已經寫yesno錯誤:

   v 
if (input == No) 
// .. 
//    v 
else if (input == Yes) 
^^^^ 

如果你希望你的程序與 「沒有沒有沒有。」 工作,你可以使用std::string::find

if(std::string::npos != input.find("no")) 
// .. 

與「是」相同。

此外,你可以這樣做幾乎不區分大小寫 - 將輸入轉換爲大寫字母(或更低,無論),然後使用find。這樣,yEs仍然是一個有效的答案。

0
bool yesno(char const* prompt, bool default_yes=true) { 
    using namespace std; 
    if (prompt && cin.tie()) { 
    *cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] "); 
    } 
    string line; 
    if (!getline(cin, line)) { 
    throw std::runtime_error("yesno: unexpected input error"); 
    } 
    else if (line.size() == 0) { 
    return default_yes; 
    } 
    else { 
    return line[0] == 'Y' || line[0] == 'y'; 
    } 
}