getline作为循环条件 - 无限循环

时间:2013-02-06 01:38:53

标签: c++ infinite-loop getline

int main(int argc, char** argv) 
{
    ifstream input;
    ofstream output;
    input.open("input.txt");
    output.open("output.txt");

    char c;

    output << "ID\tLName\tFName\tQ1 Q2 Q3 Q4 Q5 Q6 T1 T2 Final" << endl;
    output << "------------------------------------------------------" << endl;

    //Loop through each line until there is none left.
    string s;
    while (getline(input, s)) 
    {
        output << readNext(input) << "\t"; //ID
        output << readNext(input) << "\t"; //FName
        output << readNext(input) << "\t"; //LName

        output << endl;
    }
    return 0;
}

string readNext(ifstream& input) 
{
    string s;
    char c;

    if (input.peek() == ',') input.get(c);

    do {
        input.get(c);
        s += c;
    } while(input.peek() != ',');

    return s;
}

“while(getline(input,s))”行让我陷入无限循环。谁有人解释为什么?很多人都告诉我,这是阅读输入的正确方法,而不是寻找EOF。

示例输入

11111,Lu,Youmin,10,9,8,10,8,9,95,99,100 
22222,Lu,Eddie,7,8,9,10,10,10,100,92,94

1 个答案:

答案 0 :(得分:0)

试试这个。无限循环很可能是因为eof中缺少逗号。因此也检查eof将是我的建议。

string readNext(ifstream&amp; input)     {         字符串s;         char c;

    if (input.peek() == ',') input.get(c);

    do {
        input.get(c);
        s += c;
    } while(input.peek() != ',' && ! input.eof()); // Check for the end of file.

    return s;
}