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?
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->
<-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With