I want to write a program to do a process after each sentences. like this:
char letter;
while(std::cin >> letter)
{
if(letter == '\n')
{
// here do the process and show the results.
}
}
I want that when the user press the enter key (means that the sentences is finished) so that we do a process and then after showing some result the user can enter new phrases but the line if(letter == '\n') doesn't work as I expect. please tell me how I can do this. thank you.
If I understand your question and you want to trap the '\n'
character, then you need to use std::cin.get(letter)
instead of std::cin >> letter;
As explained in the comment, the >>
operator will discard leading whitespace, so the '\n'
left in stdin
is ignored on your next loop iteration.
std::cin.get()
is a raw read and will read each character in stdin
. See std::basic_istream::get For example:
#include <iostream>
int main (void) {
char letter;
while (std::cin.get(letter)) {
if (letter == '\n')
std::cout << "got newline\n";
}
}
Will generate a "got newline"
output after Enter is pressed each time.