如何允许大写和小写用户输入?

How do I allow uppercase and lowercase user input?

本文关键字:用户 输入 何允许      更新时间:2023-10-16

我是新手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;
}