Question

How do I handle white-space and return-key if the program expects the user to enter text (a name for instance).

char ch[100];
cout << "enter something: ";
cin >> ch;
cout << ch << endl;

How can the program be notified if the user

  1. just press return
  2. space + return
Was it helpful?

Solution

Like this:

#include <iostream>
#include <string>

int main()
{
    for (std::string line; std::getline(std::cin, line); )
    {
        if (line.empty())
        {
            // handle blank input
        }

        std::cout << "You said: " << line << "\n";
    }
}

This doesn't trim whitespaces yet; that can be done easily by modifying line at the beginning of the loop, e.g. using this code and adding trim(line); at the beginning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top