问题
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?
回答1:
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->
<-
回答2:
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.
来源:https://stackoverflow.com/questions/15904963/stdcin-and-why-a-newline-remains