2017-06-29 45 views
1

我有一個程序,我必須讀取文件,並且如果來自文件的輸入無效,我必須跳過該行,但是我無法弄清楚如何做到這一點。這是我的程序的一部分;雖然循環在讀取文件時陷入無限循環,但無法移動到下一行

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; 
     } 

我的程序口口聲聲說「無效的操作」,所以我想弄清楚如何在移動從那裏下一行,任何幫助,將不勝感激。

這是我輸入:

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 

回答

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; 
    }