Problem with iostream
I m using MinGW for running g++ compiler on windows. Whenever I run the following code, it the compiler gives strange results.
Code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n;
string a;
cin>>n;
getline(cin,a);
cout<<a;
return 0;
}
No problem occurs when I compile the code. But as soon as I run the code and give input for n, it never asks for the input of a and ends. I m u开发者_Python百科sing MinGW 5.1.6, is there any problem with that or is there any problem with my code?
The problem is in your code. In a nutshell, the newline you type to commit the number for n
is still stored in the input buffer as it is not numerical input, so is not consumed by n
. The getline
function then absorbs the newline and completes.
The cin>>n
reads the number, but leaves the new-line in the buffer. When you call getline
, it reads the new-line character as an empty line, prints it out, and then returns from main. One way or another, you need to get the remainder of the line out of the input buffer before you call getline
.
精彩评论