1

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!

2
  • possible duplicate of C++ cin input with spaces? Commented Jun 13, 2015 at 16:46
  • @Jigsaw Function cin.getline( input1, N ) does not deal with objects of type std::string. You can use it with character arrays but you will be unable to compare a character array with a string literal using operator ==. So you marked a wrong answer. Commented Jun 13, 2015 at 17:47

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

cin >> ignores whitespace, use getline:

getline(cin, input1);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.