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 もチェックすることをお勧めします。

文字列 readNext(ifstream& 入力) { 文字列 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;
}
于 2013-02-06T05:01:07.957 に答える