2014-10-05 92 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; 
}