user1236
user1236

Reputation: 111

Confusion about cin function at run-time

int main()
{
    cout<< "Please enter your first name (followed by 'enter'):\n";

    string first_name;  // first_name is a variable of type String
    cin >> first_name; //  read characters into first_name
    cout<<"Hello, " <<first_name<<"!\n";

    cout<<" first_name "<<" is "<< first_name <<"\n";



    cout << "Please enter you first name and age\n";
    string new_first_name = "unentered";
    int    age = -1;


    cin >> new_first_name;
    cin >> age;
    cout << "Hello, " << new_first_name << "(age " << age << ") \n";

    return 0;

}

I have the above bit of code that is basically an example from a book I've been working through.

Something rather funny happens when I compile and run that I didn't understand. On the first prompt, if I enter one name say 'Joe', then the rest of the program works fine. That is, I can enter a new name 'George" and age '23' at the second prompt and the output goes just fine.

If on the other hand, I enter two words separated by a comma in the first prompt, say 'Joe Person', then in the second prompt if I enter George 23, I get the output Person (age 0).

So it seems like it took the second name, used that in the second string prompt, and then did something with the age input. I'm surprised that it doesn't output the initialized value of -1.

Could anybody tell me what might be going on here? I would have thought that for the first prompt, the program would ignore whatever came after the first whitespace, but it appears as if it gets stored somehow and then get stored in the new_first_name variable.

Upvotes: 0

Views: 312

Answers (2)

Rahul Badgujar
Rahul Badgujar

Reputation: 142

Use the getline function to take input in std::string datatype when the input can consist space.

So you can write: getline(cin,first_name);

And it will work fine.

If you use cin instead, it will just ignore the string input after first space occurred. For example, if you gave input 'Joe Person', cin will only store 'Joe' in the first_name Variable. It will also leave 'Person' as the next thing to be read.

You should use cin with std::string only when the input string does not contain space, if it consists space, then you should go for getline(), this function is implemented in std::string class for the same purpose.

Find the complete explanation here

It will work definitely.

Upvotes: 4

Kain0_0
Kain0_0

Reputation: 319

The C++ stream extract operators, for strings, read tokens. That is anything up to the next peice of white-space.

Generally cpp-reference is a good reference for C/C++.

Upvotes: 5

Related Questions