6

Reference Why is the Console Closing after I've included cin.get()?

I was utilizing std::cin.get()

#include<iostream>    

char decision = ' ';
bool wrong = true;

while (wrong) {
    std::cout << "\n(I)nteractive or (B)atch Session?: ";

    if(std::cin) {
        decision = std::cin.get();

        if(std::cin.eof())
            throw CustomException("Error occurred while reading input\n");
    } else {
        throw CustomException("Error occurred while reading input\n");
    }

   decision = std::tolower(decision);
   if (decision != 'i' && decision != 'b')
        std::cout << "\nPlease enter an 'I' or 'B'\n";
   else
        wrong = false;
}

I read basic_istream::sentry and std::cin::get.

I chose instead to use std::getline as the while loop is executing twice because the stream is not empty.

std::string line; std::getline(std::cin, line);

As the reference I posted above states within one of the answers, std::cin is utilized to read a character and std::cin::get is utilized to remove the newline \n.

char x; std::cin >> x; std::cin.get();

My question is why does std::cin leave a newline \n on the stream?

Community
  • 1
  • 1
Mushy
  • 2,535
  • 10
  • 33
  • 54
  • 1
    Why read more than it has to? – chris Apr 09 '13 at 14:50
  • In C++ I/O is abstract. There's no concept of a console, and all I/O goes through the same underlying code. If you were reading a file you would not expect I/O operations to be line based, you would expect I/O operation to read what they needed and no more. So the same is true of console I/O as well. – john Apr 09 '13 at 14:54
  • 2
    Possible duplicate of [Why does cin command leaves a '\n' in the buffer?](http://stackoverflow.com/questions/28109679/why-does-cin-command-leaves-a-n-in-the-buffer) – Fantastic Mr Fox Mar 17 '17 at 18:59

2 Answers2

5

Because that's its default behavior, but you can change it. Try this:

#include<iostream>
using namespace std;

int main(int argc, char * argv[]) {
  char y, z;
  cin >> y;
  cin >> noskipws >> z;

  cout << "y->" << y << "<-" << endl;
  cout << "z->" << z << "<-" << endl;
}

Feeding it a file consisting of a single character and a newline ("a\n"), the output is:

y->a<-
z->
<-
engineerC
  • 2,808
  • 17
  • 31
0

It's pretty simple. For example if you would like to write a file with stored names of cities when reading it you wouldn't want to read names with newline characters. Besides that '\n' is character as good as any other and by using cin you are just fetching one character so why should it skip over anything? In most use cases when reading char by char you don't want to skip any character because probably you want to parse it somehow, When reading string you don't care about white spaces and so on.

Piotr Jaszkowski
  • 1,150
  • 9
  • 12