如果用户输入字符串,请在用户中读取 n和eof

Reading in and EOF from the user, if user enters a string?

本文关键字:用户 读取 eof 输入 字符串 如果      更新时间:2023-10-16

我想检查用户是否输入 n和eof。到目前为止,我尝试了

getline(cin, temp);
if(cin.EOF())//tried and did not work
  cout << "failed EOF";
if(temp[temp.size()] == 'n')
  cout << "n";

确定有效提取比您想象的要简单。如果提取失败,它将通过用于提取的输入流的流状态反映在程序中。More,std::getline()返回该流(当隐式转换为布尔值时)将检查其流状态是否适当的位。您可以利用此功能并将提取包含在if语句中,该语句将隐式将其参数转换为布尔值:

if (std::getline(std::cin, temp))

如果提取成功执行,则if语句将执行。如果您想通过流状态响应用户,可以在流中设置异常蒙版,并检查任何抛出的异常:

if (std::getline(std::cin, temp))
{
    std::cout << "Extraction produced: " << temp << std::endl;
}
try {
    std::cin.exceptions(std::ios_base::failbit | std::ios_base::eofbit);
} 
catch (std::ios_base::failure&)
{
    std::ios_base::iostate exceptions = std::cin.exceptions();
    if ((exceptions & std::ios_base::eofbit) && std::cin.eof())
    {
        std::cout << "You've reached the end of the stream.";
    }
}

上面只是一个示例。我没有试图编译它。:)