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

查看:52
本文介绍了if语句中的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;
 }

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

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