输入答案时,如何区分大小写无关紧要
How to make case sensitivity not matter when inputting an answer?
所以我在学习编程,我了解变量、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;
}
相关文章:
- 数到第n个楼梯的路(顺序无关紧要)
- 切换大小写后如何阻止变量重置?
- 无法找到简单的开关大小写枚举错误
- 仿射密码解密,输出大小写不同
- 编写宏函数来更改字符串的大小写?
- 使字母检查不区分大小写
- 如何执行不区分大小写的字符串比较?
- 函数中的切换大小写语句不会切换C++
- CMake 添加不区分大小写的源文件
- 如何在不同的开关大小写语句上使用对象的类成员函数?
- 如何以 if else 或切换大小写格式对自动和编码?
- 有没有一种方法可以忽略Qt c++中的文件名大小写敏感性?
- 标题与标准标题具有相同名称但大小写不同的问题
- Rand()大小写开关在多次迭代后运行到无穷大
- 在这种情况下,如何在基类中设计开关大小写函数
- 提升program_option配置文件的不区分大小写的解析
- 复数大小写中的C++运算符 ->
- 如何提升Perl正则表达式匹配,支持区分大小写/不区分大小写
- 计算唯一单词的数量(大小写对此计数无关紧要)
- 输入答案时,如何区分大小写无关紧要