-4

Input problem in c++ and java if we input a string after an integer it will skip it go to the next statement.

    string name;
int age;
cout<<"Enter age";
cin>>age;
cout<<"Enter name";
getline(cin,name);



cout<<name;
cout<<age;

getch();

above code not taking name it skip this line.what aproblem with it......???

Gray
  • 7,050
  • 2
  • 29
  • 52

3 Answers3

2

When the integer value is read the [Enter] introduced to finish the line is still in the stream, and getline(cin,name) reads that [Enter].

To solve the problem, first flush cin before getting the string:

string name;
int age;
cout<<"Enter age";
cin>>age;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignores all enters
cout<<"Enter name";
getline(cin,name);

cout<<name;
cout<<age;

getch();
Community
  • 1
  • 1
xorguy
  • 2,594
  • 1
  • 16
  • 14
2

I'll answer for C++ only, as only C++ code is present.

std::getline will consumes the newline character left over the input stream by previous operator >>, and hence it returns.

A simple work around is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

before using std::getline

#include<limits>
// ....
string name;
int age;
cout<<"Enter age";
cin>>age;

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

cout<<"Enter name";
getline(cin,name);
P0W
  • 46,614
  • 9
  • 72
  • 119
0
std::cin >> age;
std::getline(std::cin, name);

Let's say the user enters the integer 5. This is what the input stream will look like:

5\n
...

Note that the above could vary. The user could enter an integer and subsequently a space character. Both are equally valid situations.

That is, the user enters the value and hits return to submit. operator >> is formatted so that the integer will be consumed, but once it finds a new line or whitespace extraction will cease. After the input operation, the new line should still be in the stream.

\n
...

Now, let's see the content for name:

\n
"Bruce Wayne"\n

When getline executes, once it finds a new line in the stream it will stop searching for new input. The new line from the previous extraction was still in the stream, so the input was stopped immediately. Nothing was extracted!

Fortunately, we can use the ignore method to discard the new line from the stream:

std::cin >> age;
std::cin.ignore(); // ignore the next character

std::getline(std::cin, age);

By default, std::cin.ignore will discard the next character from the stream when given 0 arguments.

Here is a live example.

David G
  • 94,763
  • 41
  • 167
  • 253