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

C++ multiple strings inside an if statement(if语句中的C ++多个字符串)
本文介绍了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 ++多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)