meysamimani
meysamimani

Reputation: 335

new line character(enter key) in C++

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.

Upvotes: 2

Views: 1997

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84531

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.

Upvotes: 5

silverfox
silverfox

Reputation: 1662

You want to use getline() probably, because std::cin will stop at whitespaces:

#include <iostream>

int main()
{
    std::string x;
    while(x != "stop") //something to stop
    {
        std::cout << "Your input : ";
        std::getline(std::cin, x);
        std::cout << "Output : " << x << "\n"; //Do other stuff here, probably
    }
    std::cout << "Stopped";
}

Result:

Your input : test1
Output : test1
Your input : abc def ghi
Output : abc def ghi
Your input : stop
Output : stop
Stopped

Upvotes: 4

Related Questions