0

I have the following piece of code in which the cin is before getline and the getline is capturing the new line hence not assigning any value to its variable; The code is

int main(){
    string a,b;
    int n;
    cin>>n;
    getline(cin,a);
    cout<<a;
    return 0;
}

PS:As soon as I press enter after entering a No , Program ends(i..e getline captures newline and so a is null.It would be great if someone could suggest me a resource for learning basic I/O Concepts in Cpp)

nosid
  • 48,932
  • 13
  • 112
  • 139
  • I suggest reading [**Standard C++ IOStreams and Locales**](http://www.amazon.com/Standard-IOStreams-Locales-Programmers-Reference/dp/0321585585) as it's good for both novice and advanced learners. – David G Jun 28 '14 at 17:45

2 Answers2

4

When you enter "No", which is not a valid integer, your cin stream is in an error state after the cin >> n expression. Therefore, no further input will work, and in particular, your getline will not try to read a line.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
3

You have to discard the new line character you inputed before calling the next getline (if not, you simply read a single new line character) :

int main()
{
    string a,b;
    int n;
    cin>>n;
    cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n'); // <-- Here
    // Or cin >> ws suggested by @0x499602D2
    getline(cin,a);
    cout<<a;
    return 0;
}

Notes:

  • You should check the success/failure of each IO operation, including cin >> n.
  • en.cppreference.com is a good starting point as for the I/O streams documentation.
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • `ignore()` really isn't needed here. All he needs to do is clear the newline character, hence `std::cin >> std::ws` is all that's needed. – David G Jun 28 '14 at 17:42
  • Thx for the comment. Whats the difference ? – quantdev Jun 28 '14 at 17:46
  • Well 1: it's shorter. 2: It only clears whitespace (a newline is parsed as whitespace by default in IOStreams) while `ignore()` clears any character. – David G Jun 28 '14 at 17:47
  • Its a matter of taste, I find `ignore` more readable (and my ignore only ignores new lines, look at the second argument, not other whitespaces). I add your suggestion. – quantdev Jun 28 '14 at 17:50
  • I concede that it's a matter of taste in this context, but your example doesn't clear newlines *exclusively*. The second argument is the character at which `ignore()` will cease ignoring characters. So what the function is doing is discarding characters until it discards `max()` characters or until it finds the `'\n'` character, whichever comes first. Also, it's not `cin << ws` but `cin >> ws`. – David G Jun 28 '14 at 17:55