tags:

views:

73

answers:

2

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 using MinGW 5.1.6, is there any problem with that or is there any problem with my code?

+2  A: 

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.

Jerry Coffin
+3  A: 

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.

fbrereto
what should I do to input a number and as well as input a string containing whitespaces.
vaibhav
@viabhav: A simple solution might be to get rid of any whitespace in the buffer: `std::cin >> n >> std::ws;` [See this](http://stackoverflow.com/questions/1243428/convert-string-to-int-with-bool-fail-in-c/1243435#1243435) for a more complete solution.
GMan
thanks a lot.. u solved my grr8 problem.. :)
vaibhav