Jve*_*eto 4 c++ string conditional-statements
我在尝试检查if语句中的多种可能性时遇到了问题.
用户输入一个字符串,然后我针对多种可能性检查该字符串.
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;
}
Run Code Online (Sandbox Code Playgroud)
所以这只是我想要完成的一个简单的例子.在我的程序中,这些if语句在函数中,我正在使用#include [string].(我甚至不确定"6"或"7"是否可行,但我现在甚至无法测试我的代码:(所以现在在我的代码中,如果用户输入6,我的程序将运行并分配任何想法都是7的值.
谢谢.
我想变量的类型theString是std::string.否则至少这个比较
theString == "Seven"
Run Code Online (Sandbox Code Playgroud)
没有意义,
if语句中的条件
if (theString == "Seven" || "seven" || "7")
Run Code Online (Sandbox Code Playgroud)
相当于
if ( ( theString == "Seven" ) || ( "seven" ) || ( "7" ) )
Run Code Online (Sandbox Code Playgroud)
并且总是产生,true因为至少字符串文字的地址"seven"不等于零.所以这个子表达式( "seven" )提供了整个表达式将等于true.
你应该写
if (theString == "Seven" || theString == "seven" || theString == "7")
Run Code Online (Sandbox Code Playgroud)
但最初将字符串转换为大写或小写更好.
例如
#include <algorithm>
#include <string>
#include <cstring>
//...
std::transform(theString.begin(), theString.end(), theString.begin(),
[](char c) { return std::toupper((unsigned char)c); });
if (theString == "SEVEN" || theString == "7")
{
theInt = 7;
cout << "You chose: " << theInt << endl;
}
else if ( theString == "SIX" || theString == "6" )
{
theInt = 6;
cout << "You chose: " << theInt << endl;
}
Run Code Online (Sandbox Code Playgroud)
使用std::setc++11,您可以使用与您的语法相似的语法来完成一个衬垫。
检查这个:
#include <iostream>
#include <string>
#include <set>
int main()
{
if( (std::set<std::string>{"Seven", "seven", "7"}).count("seven") )
{
std::cout << "foo\n";
}
std::string theString("6");
if( (std::set<std::string>{"Six", "six", "6"}).count(theString) )
{
std::cout << "bar\n";
}
}
Run Code Online (Sandbox Code Playgroud)
注意:从 c++20contains开始,您可以使用count
您无法像 C++ 中那样将一个变量与多个值进行比较。你应该这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)