简体   繁体   中英

C++ String Input as if/else statement condition

I saw a similar question to mine: C++ string variables with if statements

The only difference between his situation and mine is that I would like the condition to be if a string with a space is matching a certain string.

Here is my code:

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

For some reason, the if statement is not picking up the string. However, if the conditions is:

if (input1 == "login"

It works. I cannot find a way to use a string with a space in it with a condition. I am wondering if maybe the if statement is okay but that the cin is deleting the space.

Thank you!

You should use standard function std::getline instead of the operator >>

For example

if ( std::getline( std::cin, input1 ) && input1 == "log in" )
{
    std::cout << "Please enter your Agent ID." << std::endl;
}

cin >>忽略空格,使用getline:

getline(cin, input1);

You need to read the entire line with spaces with std::getline , it will stop when finds a newline \\n or N-1 characters. So, just do the reading like this:

cin.getline( input1, N );

Where N is the max number of character that will read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM