Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cin reading string into int type returns 0 [duplicate]

Tags:

c++

#include <iostream>
using namespace std;
int main()
{
    cout << "Please enter your name and age\n";
    string first_name;
    int age;
    cin >> first_name;
    cin >> age;
    cout << "Hello, " << first_name << " (age " << age << ")!\n";
}

If I type in Carlos for age or any other string I get a 0. How does this work(why)?

like image 725
Robert Rocha Avatar asked Dec 08 '22 18:12

Robert Rocha


1 Answers

Not sure why the question got down/close votes as it's clearly stated and not broad (and judging by the comments, many people don't know the answer)...

Anyway, for the code:

int age;
cin >> age;

if the input stream did not contain any digits, then the stream is put into a fail state and age is set to 0. The characters in the input stream remain there; they can be read by a future read operation once the fail state is cleared.

The behaviour of operator>> is summarized on cppreference , the full description in the standard is somewhat complicated.

Note: This changed in C++11; commentors reporting garbage output are either running compilers in pre-C++11 mode, or bugged ones.

like image 186
M.M Avatar answered Dec 21 '22 02:12

M.M