如果用户输入字符串,请在用户中读取 n和eof
Reading in and EOF from the user, if user enters a string?
我想检查用户是否输入 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."; } }
上面只是一个示例。我没有试图编译它。:)
相关文章:
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 从标准输入读取文件后读取用户输入
- 读取一组用户输入,按升序排序,然后打印结果
- 尝试读取.txt文件并根据用户输入的字母拉出特定行
- 读取用户必须提供一些参数的文件
- C++使用用户名/SID 或备用读取任何窗口用户 HKEY
- 如何让这个C++代码从用户那里读取五个整数而不是一个整数?
- 为什么此代码无法正确读取用户输入
- 如何读取带有空格的序列并在用户按C++中的"输入"时停止?
- FSTREAM的问题读取确定,但不编写用户输入字符串
- C ++读取用户输入的字符一个一个符号
- 是否有任何方法可以在用户输入文本时读取字符
- 用户输入的文件将从C 读取
- 如何制作一个从文件中读取密码并与用户编写的密码进行比较的 c++ 程序
- 在 MFC 应用中定义和读取用户定义的资源
- 在读取数据文件时,如何找到用户字符串输入的字谜?
- C++ 如何从用户输入中读取第一个字符并忽略 rest(字符类型)
- 以简单格式"c:filessample.txt"从用户读取文件路径
- 为游戏创建用户(读取和解析CSV文件)
- 从用户读取字符串