if you "read in" std::noskipws
, then reads will stop skipping whitespace. This means when you read in a single character, you can read in spaces and newlines and such.
#include <iostream>
#include <iomanip>
int main() {
std::cin >> std::noskipws; //here's the magic
char input;
while(std::cin >> input) {
std::cout << ">" << input << '\n';
}
}
when run with the input:
a
b
c
produces:
>a
>
>
>b
>
>
>c
So we can see that it read in the letter a
, then the enter key after the newline, then the empty line, then the letter b
, etc.
If you want the user to hit the enter key after entering a number, you'll have to handle that in your code.
If the user is simply entering one "thing" per line, there's actually an easier way:
#include <iostream>
int main() {
std::string line;
while(std::getline(std::cin, line)) {
std::cout << line << '\n';
}
}
This will read the characters from the input until the end of the line, allowing you to read lines with spaces, or lines with nothing at all. Be warned that after you use std::cin >>
it commonly leaves the newline key in the input, so if you do a std::getline
right after it will return an empty string. To avoid this, you can use std::cin.ignore(1, '\n')
to make it ignore the newline before you try to use std::getline
.