我看到了一个与我类似的问题:C++ string variables with if statements
他的情况和我的唯一区别是,我希望条件是如果带空格的字符串与某个字符串匹配。
这是我的代码:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string input1;
cout << "Welcome to AgentOS V230.20043." << endl;
cout << "To log in, please type \"log in\"" << endl;
cin >> input1;
if (input1 == "log in")
{
cout << "Please enter your Agent ID." << endl;
}
return 0;
}
出于某种原因,if 语句没有提取字符串。但是,如果条件是:
if (input1 == "login"
它有效。我找不到一种方法来使用带有条件的字符串。我想知道 if 语句是否可以,但 cin 正在删除空格。
谢谢!
最佳答案
您应该使用标准函数 std::getline
而不是 operator >>
例如
if ( std::getline( std::cin, input1 ) && input1 == "log in" )
{
std::cout << "Please enter your Agent ID." << std::endl;
}
关于C++ 字符串输入作为 if/else 语句条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30821036/