0
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
4

1 回答 1

0

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

string readNext(ifstream& input) { string s; 字符 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;
}
于 2013-02-06T05:01:07.957 回答