4

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?

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
Vaibhav
  • 6,620
  • 11
  • 47
  • 72

2 Answers2

4

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
  • 35,429
  • 19
  • 126
  • 178
  • what should I do to input a number and as well as input a string containing whitespaces. – Vaibhav Aug 25 '10 at 18:27
  • 3
    @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. – GManNickG Aug 25 '10 at 18:55
3

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
  • 476,176
  • 80
  • 629
  • 1,111