Problem with iostream

I am using MinGW to run the g ++ compiler on Windows. Whenever I run the following code, it compiler gives strange results.

the code:

#include <iostream> #include <cstring> using namespace std; int main() { int n; string a; cin>>n; getline(cin,a); cout<<a; return 0; } 

The problem does not occur when compiling the code. But as soon as I run the code and give input for n, it never asks for input a and never ends. I am using MinGW 5.1.6, are there any problems with this or are there any problems with my code?

+4
source share
2 answers

The problem is in the code. In a nutshell, the new line you enter to fix the number for n still stored in the input buffer, since it is not a numerical input, so n not consumed. The getline function then absorbs the new line and exits.

+4
source

cin>>n reads the number, but leaves a new line in the buffer. When you call getline , it reads the newline as an empty string, prints it, and returns from the main. Somehow, you need to get the rest of the line from the input buffer before you call getline .

+3
source

All Articles