输入答案时,如何区分大小写无关紧要

How to make case sensitivity not matter when inputting an answer?

本文关键字:大小写 无关紧要 何区 答案 输入      更新时间:2023-10-16

所以我在学习编程,我了解变量、if-else语句、cin和cout。因此,对于一个入门项目,我只是创建一个控制台应用程序,询问用户问题,例如年龄、位置等。其中一个我想要一个简单的"是"或"否"的答案。我已经设法做到了这一点,但用户输入的内容必须与if语句中的单词大小写相同。即,如果语句包含大写"Y"的"是"。如果用户在没有大写"Y"的情况下输入"是",则程序将失败。

if语句判断它是否为"是",如果是,则提供积极反馈。如果"否",则提供负面反馈。

无论答案是"是"、"是"还是"是",我怎么能做到呢?

u可以获取输入字符串,将其全部更改为大写\小写,然后检查它是"YES"还是"YES"。

对于输入中的每个字符:tolower(c)

一个简单的方法是首先将用户输入转换为小写字母。然后将其与较低的是或否进行比较。

#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;
    }
}

你可以试试这个:

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