std::cin 语法 当遇到 EOF 时

std::cin syntax when encounter EOF

本文关键字:EOF 遇到 语法 cin std      更新时间:2023-10-16

这段代码只是为了实现一个函数,当你输入两个相同的字符串时,函数停止。

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;
....
}