if语句中的C ++多个字符串

2022-01-20 00:00:00 string conditional-statements c++

我在尝试检查 if 语句中的多种可能性时遇到问题.

I'm having an issue trying to check against multiple possibilities in an if statement.

用户输入一个字符串,然后我检查该字符串是否有多种可能性.

The user inputs a string, and then I check that string against multiple possibilities.

if (theString == "Seven" || "seven" || "7")
 {
   theInt = 7;
   cout << "You chose: " << theInt << endl;
 }
else if (theString == "Six" || "six" || "6")
 {
   theInt = 6;
   cout << "You chose: " << theInt << endl;
 }

所以这里只是一个我想要完成的简单示例.在我的程序中,这些 if 语句在一个函数中,我正在使用 #include [string].(我什至不确定6"或7"是否可能,但我现在什至无法测试我的代码:(所以现在在我的代码中,如果用户输入 6,我的程序将运行并将值 7 分配给 theInt.有什么想法吗?

So there's just a quick example of what I'm trying to accomplish. In my program, these if statements are in a function, and I am using #include [string]. (I'm not even sure if "6" or "7" is possible, but I can't even test my code right now :( So right now in my code, if the user input 6, my program would run and assign a value of 7 to theInt. Any ideas?

谢谢.

推荐答案

你不能像在 C++ 中那样将一个变量与多个值进行比较.你应该这样做:

You cannot compare a variable against multiple values like that in C++. You should be doing:

if (theString == "Seven" || theString == "seven" || theString ==  "7")
 {
   theInt = 7;
   cout << "You chose: " << theInt << endl;
 }
else if (theString == "Six" || theString == "six" || theString == "6")
 {
   theInt = 6;
   cout << "You chose: " << theInt << endl;
 }

相关文章