1

I'm not sure how std::cin actually takes inputs from the stream.

For example, my code:

#include <iostream>

int main()
{
    std::cout<<"Pick 1 or 2: ";
    int choice;
    std::cin>>choice;

    //std::cin.ignore(32767,'\n');

    std::cout<<"Now enter your name: ";
    std::string name;
    std::getline(std::cin,name);

    std::cout<<"Hello, "<<name<<", you picked "<<choice <<'\n';
    return 0;
}

When I comment out the std::cin.ignore, the console prints "Pick 1 or 2: ", I entered 1 and it skips waiting for me to enter my name. Instead, I saw "Hello, , you picked 1 choice".

Actually, does cin even takes the null character in the stream, I wonder?

Biffen
  • 5,354
  • 5
  • 27
  • 32
  • 1
    You type in `1` followed by carriage return aka `\n` character. `std::cin>>choice` reads `1`, but leaves `\n` in the stream. `std::getline` encounters the carriage return first thing, consumes it and reads an empty line. `ignore` call, when present, consumes the `\n`, so that `getline` actually reads the second line, rather than the leftover of the first. – Igor Tandetnik Feb 12 '18 at 03:54
  • I have thought about that. However, I wonder why it did not print out "Hello, " -> newline: ", you picked 1" – Thong Nguyen Thanh Feb 12 '18 at 03:57
  • `getline` reads characters up to and including newline. It puts all those characters - except the newline - into the string. An empty line produces an empty string, not a one-character string containing a newline. – Igor Tandetnik Feb 12 '18 at 04:01

1 Answers1

0

When you input something using cin and hit enter, a '\n' char gets into the cin buffer. So to clear this buffer, you can use std::cin.ignore(32767,'\n') and that should clear the buffer up for the string that you want.

abuv
  • 170
  • 1
  • 1
  • 12
  • I have thought about that. However, I wonder why it did not print out "Hello, " -> newline: ", you picked 1" – Thong Nguyen Thanh Feb 12 '18 at 04:01
  • Good question! This is because cout will take null termination into account and will ignore white spaces and \n when passing in variables. For example, you can write lines out to console using cout and it will read the spaces without terminating the cout command if written as a \n or endl(), while writing something with spaces or '\n' into the cin buffer will look for a new line in the code. – abuv Feb 12 '18 at 04:26