C if语句中的多个字符串 [英] C++ multiple strings inside an if statement

查看:163
本文介绍了C if语句中的多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试检查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,则我的程序会运行并将int赋值为7。有什么想法吗?

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;
 }

这篇关于C if语句中的多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆