如何允许大写和小写用户输入?
How do I allow uppercase and lowercase user input?
我是新手C++程序员。我写了一个基本的情绪检查器,它根据从数组中获取的回复做出反应。我想知道如何使回复在输入时以大写和小写形式工作?例如,当用户输入"快乐"或"快乐"时,两者都可以工作。我已经阅读了有关 switch 语句和 toupper/tolower 的信息,但我迷失了如何为我的代码实现这些。在这里:
// Array of emotions
string positive[] = {"happy", "pleased", "joyful", "excited", "content", "cheerful", "satisfied", "positive"};
string negative[] = {"unhappy", "sad", "depressed", "gloomy", "down", "glum", "despair", "negative"};
string reply;
cout << "Please state your current emotions." << endl;
cin >> reply;
for (int i = 0; i < 10; i++)
if (reply == positive[i])
{
cout << "I am glad to hear that!" << endl;
}
else if (reply == negative[i])
{
cout << "I am sorry to hear that." << endl;
}
您可能希望在读入字符串后添加一个步骤来处理字符串reply
。
一种解决方案是遍历reply
的长度,并对字符串中的每个字符调用tolower
。
从 http://www.cplusplus.com/reference/cctype/tolower/修改的示例
int i = 0;
while (reply[i]) {
c=reply[i];
reply[i] = tolower(c);
i++;
}
然后,当您比较字符串时,您无需担心大小写。
首先,编写一个名为equals的函数来比较两个世界是否相同,方法是将字符串的所有字符转换为小写。 示例:
bool equals(string status, string userInput)
{
//lowercaseStatus = convert userInput to lowercase
//lowercaseUserInput = convert status to lowercase
return lowercaseStutus == lowercaseUserInput;
}
然后在 for 循环中使用函数:
for (int i = 0; i < 10; i++)
if (equals(positive[i],reply))
{
cout << "I am glad to hear that!" << endl;
}
else if (equals(negative[i],reply))
{
cout << "I am sorry to hear that." << endl;
}
相关文章:
- C++如何通过用户输入删除列表元素
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- C ++奇怪的数组由用户输入
- 如何允许大写和小写用户输入?
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 如何使用用户输入变量制作二维数组?
- 用户输入字符串的文件附加问题..C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?