虽然循环在读取文件时陷入无限循环但无法移动到下一行

时间:2017-06-29 20:26:56

标签: c++

我有一个程序,我必须读取一个文件,如果文件中的输入无效,我必须跳过该行,但我无法弄清楚如何做到这一点。这是我的计划的一部分;

int main ()
{

    int line=0;

    ifstream    infile; //INPUT input file stream
    ofstream    outfile; //OUTPUT output file stream

    infile.open("inputPartd.txt");
    if (! infile)
    {
        cout <<"Problem opening input file inputPartd.txt"<<endl;
        return 1; //not successful
    }

    outfile.open("resultsPartd.txt");
        if (! outfile)
        {
            cout <<"Problem opening output file resultsPartd.txt"<<endl;
            return 1; //not successful
        }



    while (true)
    {
        double num1;
        double num2;

        int intnum1;
        int intnum2;

        char mathOperator;

        double addition;
        double subtraction;
        double multiplication;
        int division; //division is using remainders so float isnt needed
        double power;

        double remainder;

        line = line +1;


        //reading numbers from the file
        if (infile >> num1 >> num2 >> mathOperator)
        {}

        else
        {
            cout << "INVALID OPERAND";
            continue;
        }


        if(infile.eof())
            break;
        if(infile.fail())
        {
            // report error
            break;
        }

我的程序一直在说&#34; INVALID OPERAND&#34;所以我想弄清楚如何从那里继续下一行,任何帮助都将不胜感激。

以下是我的意见:

10 a +
what is this
25 35 -
-1 -1 *
9 6 /
0 1 /
1 0 /
2 4 !
2 4 more!
2 3 ^
2.0 3 ^
2 0.5 ^
0 1 ^
0.0 0.0 ^
10.0 5 +
10.5 5 +
3 2 x
-10000 -10000 *
3.14159 3.14159 *
3 3 /
0.0 0.0 /
32 0.2 ^
1 1 plus

1 个答案:

答案 0 :(得分:0)

输入规则如何?

10 a +

相同
10
a
+

假设它们不是,那么最简单的方法是使用令牌解析来拆分行解析。

使用std::getline( std::istream, string );,您可以阅读整行。 然后尝试用格式解析它。

这确保即使您不理解数据,也要继续吃输入。

Putting the read line into a `stringstream` allows the line to be parsed with similar code.


while (true)
{
    double num1;
    double num2;

    int intnum1;
    int intnum2;

    char mathOperator;

    double addition;
    double subtraction;
    double multiplication;
    int division; //division is using remainders so float isnt needed
    double power;

    double remainder;
    std::string strResult;
    std::getline( infile, strResult );
    std::stringstream currentLine( strResult );
    line = line +1;


    //reading numbers from the file
    if (currentLine>> num1 >> num2 >> mathOperator)
    {}

    else
    {
        cout << "INVALID OPERAND";
        // continue;  <<< This doesn't help, as it goes to the beginning of the while loop, not allowing for eof / fail checks.
    }


    if(infile.eof())
        break;
    if(infile.fail())
    {
        // report error
        break;
    }