Cin() 为用户预键入 "y"

Cin() pretype "y" for user

cout << "CONFIRM EXIT [y/n]: ";
cin >> inputChar

控制台应该说:

CONFIRM EXIT [y/n]: y

我看过:

int number(20);
string numStr;
cout << "Please give a number [default = " << number << "]: ";
getline(cin, numStr);
number = ( numStr.empty() ) ? number : strtol( numStr.c_str(), NULL, 0);
cout << number << endl;

^^ User input(cin) - Default value - 作者:组件 10

有更好的方法吗?

谢谢!

是这样的吗?

std::string askUser(const std::string& question, const std::string& default_answer)
{
    std::cout << question << ": " << default_answer << '\r';
    std::cout.flush();
    std::cout << question << ": ";


    std::string answer; 
    std::getline(std::cin, answer);
    answer = answer.empty() ? default_answer : answer;
    return answer;
}

int main()
{
    std::string answer = askUser("CONFIRM EXIT [y/n]", "y");
    std::cout << "Answer is '" << answer << "'" << std::endl;
    system("PAUSE");
}