0

这段代码只是为了实现一个功能,当您输入两次相同的字符串时,该功能将停止。

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++入门》中的一个练习,答题书上的代码也没有解决问题。

4

3 回答 3

1

您对之前输入的内容并不太具体。当>> astd::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;
}
于 2012-05-30T09:13:43.360 回答
0

我认为当你击球时CTRL-D,你会中断跑步。

试试这个:

while (cin >> c_data) {

if (c_data == "<EXIT>") break;

....
}
于 2012-05-30T07:36:44.877 回答
0

这可能是一个解决方案:

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;
于 2012-05-30T07:55:37.840 回答