문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top