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!

Community
  • 1
  • 1
will smith
  • 77
  • 1
  • 2
  • 9
  • possible duplicate of [C++ cin input with spaces?](http://stackoverflow.com/questions/5838711/c-cin-input-with-spaces) – rbaleksandar Jun 13 '15 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. – Vlad from Moscow Jun 13 '15 at 17:47

3 Answers3

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

cin >> ignores whitespace, use getline:

getline(cin, input1);
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
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.

Skatox
  • 4,237
  • 12
  • 42
  • 47