std::cin 语法 当遇到 EOF 时
std::cin syntax when encounter EOF
这段代码只是为了实现一个函数,当你输入两个相同的字符串时,函数停止。
string predata;
string c_data; //current data
cout << "please input string data" << endl;
//loop
while (cin >> c_data) {
if (c_data == predata) {
cout << "the " << c_data << " is the same one" << endl;
break;
}
else {
predata = c_data;
}
cout << "please input next word" << endl;
}
if (c_data != predata)
cout << "there's no repeated word" << endl;
问:当我使用 CTRL-D 停止 cin 时,c_data不会改变,并且永远不会输出"没有重复的单词",那么我该如何判断?
PS:这是《c++入门》中的一个练习,答案书中的代码也没有解决问题。
你对
以前输入的内容不太具体。 当>>
对于失败std::string
,它将右操作数留在未指定的状态。 (如果这真的是书中的代码,我会把书扔掉。
这里最简单的解决方案是使用标志:
std::string previous;
std::string current;
bool duplicateSeen = false;
std::cout << "Please input initial string" << std::endl;
std::cin >> previous;
if ( std::cin ) {
// Code needs at least one input to compare...
while ( ! duplicateSeen && std::cin >> current ) {
duplicateSeen = current == previous;
previous = current;
std::cout << "Please input the next word" << std::endl;
}
}
if ( duplicateSeen ) {
std::cout << '"' << previous << "" is duplicated" << std::endl;
} else {
std::cout << "No repeated words" << std::endl;
}
这可能是一个解决方案:
c_data = "eof is setted";
while (cin >> c_data) {
if (c_data == predata) {
cout << "the " << c_data << " is the same one" << endl;
break;
}
else {
predata = c_data;
c_data = "eof is setted";
}
cout << "please input next word" << endl;
}
if (c_data != predata)
cout << "there's no repeated word" << endl;
我认为
当你按下CTRL-D
时,你会中断跑步。
试试这个:
while (cin >> c_data) {
if (c_data == "<EXIT>") break;
....
}
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 编译包含字符串的代码时遇到问题
- 遇到新行时,有没有办法停止istream_iterator
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 在 for 循环中查找问题时遇到困难
- 创建结构的数组时遇到分段错误
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 为什么我遇到分段错误?
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 这些是什么样的错误?即使我不在 Linux 上工作,我也遇到了 Linux 错误
- 为什么我在尝试模板时遇到视觉工作室C++错误
- 如何从文本文件中读取数值,直到遇到字符类型?
- 从其他类访问类时遇到问题
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 打印问题.我在数组中打印值时遇到一些问题
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 使用静态成员声明类时遇到问题
- C++使用cin.get来获取一个字符,但在遇到EOF时不会结束while循环
- std::cin 语法 当遇到 EOF 时