我是一名新手C ++程序员。我已经编写了一个基本的情绪检查器,该检查器根据从数组中获取的答复做出反应。我想知道如何做到这一点,以便键入时,无论大写还是小写,回复都起作用?例如。当用户输入“ happy”或“ Happy”时,两者都可以使用。我已经读过关于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;
}
答案 0 :(得分:0)
读入后,您需要添加一个步骤来处理字符串reply
。
一种解决方案是遍历reply
的长度并在字符串中的每个字符上调用tolower
。
从http://www.cplusplus.com/reference/cctype/tolower/修改的示例
int i = 0;
while (reply[i]) {
c=reply[i];
reply[i] = tolower(c);
i++;
}
然后,当您比较字符串时,您无需担心大小写。
答案 1 :(得分:0)
首先,编写一个名为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;
}