2014-10-05 91 views
-4

所以我正在學習編程和我理解變量,如果其他語句,cin和cout。 因此,對於初學者項目,我只是創建一個控制檯應用程序,詢問用戶的問題,如年齡,位置等。 其中之一,我想只是一個簡單的是或否的答案。我設法做到了這一點,但用戶輸入的內容必須與if語句中的單詞相同。即如果陳述包含「是」且大寫字母「Y」。如果用戶輸入「是」而沒有大寫字母「Y」,則程序失敗。如何在輸入答案時區分大小寫?

if語句看到它是否爲「是」,如果是,則提供正面反饋。如果「否」,那麼它提供負面反饋。

無論答案是「是」,「是」還是「YeS」,我該如何做?

回答

1

你可以把輸入的字符串全部改爲大寫\小寫,然後檢查它是「是」還是「是」。

在輸入每個字符:tolower的(C)

0

一個簡單的方法來做到這一點是首先將用戶輸入轉換爲小寫字母。然後將它與小寫字母「是」或「否」進行比較。

#include <iostream> 
// This header contains to tolower function to convert letters to lowercase 
#include <cctype> 
#include <string> 

using namespace std; 

int main() 
{ 
    string user_input; 
    cin >> user_input; 

    // Loop over each letter and change it to lowercase 
    for (string::iterator i = user_input.begin(); i < user_input.end(); i++){ 
     *i = tolower(*i); 
    } 

    if (user_input == "yes") { 
     cout << "You said yes" << endl; 
    } else { 
     cout << "You did not say yes" << endl; 
    } 
} 
0

你可以試試這個:

int main(void) 
{ 

    string option; 
    cin>>option; 
    transform(option.begin(), option.end(), option.begin(), ::tolower); 
    if(option.compare("yes")==0){ 
     cout<<option; 
    } 
    return 0; 
}