2011-04-10 114 views
0
unsigned short n = 0; 
    while (!in.eof()) 
    { 
     in >> opString;  //Read in string from file 
     //Read the string from file character by character 
     for (int i = 0; i < opString.size(); i++) 
     { 
      if (!op1b) //If we do not yet know our first operand (op1b = false, b stands for bool, clever naming eh?) 
      {  //Check if our next item is an operator. If it is... 
       if (!(opString[i] == '+' || opString[i] == '-' || opString[i] == '*' || opString[i] == '/' || opString[i] == '$')) 
        op1[i] = opString[i]; 
       else  //We finally know it since when we hit an symbol, our first number is known; do not repeat this if block 
        op1b = true;     
       n++; 
      } 

      if (op1b && !operb)  //If we know our first operand but not our operator... 
      { 
       oper = opString[i];  //Find out what our operator is. Now we know it (operb = true) 
       operb = true; 
       i++;    //We increment i because if we did not we'd double dip on the if statement below and wind up 
      }       // with an operator tacked onto the beginning of the second operand 

      if (op1b && operb)  //If we know our first operand and the operation, let's find operand #2 
      { 
       if (opString[i] == '=') 
        break; 
       else 
       { 
        op2[i-n] = opString[i]; 
        j++; 
       } 
      } 
     } 
     cout << "Op 1: " << op1.c_str() << endl << "Oper: " << oper.c_str() << endl << "Op 2: " << op2.c_str() << endl; 
    } 
    return 0; 
} 

我在這裏是(一開始)一個程序,它的目的是從文本文件中讀取字符串以將十六進制操作數添加到一起。這些字符串的形式爲「op1OperatorOp2 =」(減去引號)。我剛剛開始。我試圖通過逐個字符地讀取文件(opString)中的字符串(如for循環中的i所示)來取出op1,op2和運算符(所有字符串)。 while循環只是檢查它不是fstream變量的文件結尾。 op1b和operb是bool值,有助於確定我們何時知道我們的第一個操作數和操作符是什麼(然後我們何時可以計算出操作符編號2)。C++一次給兩個字符串賦值

但是,當我從字符串中提取op2時,我的op1被替換爲op2的值,即使我只說op2 [whatever] = opString [i],那裏我很久以前就會在op1甚至會出現這種情況。

例如:如果從文件進入的字符串是「3 + 2 =」,op1應該得到3,操作符應該得到+,op2應該得到2.然而,op2總是結束與op1相同循環的結尾。因此,取代op1 = 3,oper = +,op2 = 2,我最終得到op1 = 2,oper = +,op2 = 2.

是否存在某些未記錄的C++功能?我無法弄清楚爲什麼會出現這種情況。是因爲我在循環中嗎?我應該分手嗎?然而,我不明白爲什麼這會有所作爲。謝謝。

+1

'但我認爲複製/粘貼所有內容比粘貼while循環更容易,然後討論細節。 - 寫起來更容易,但更難讓我們閱讀,理解和幫助你。 – 2011-04-10 04:34:05

+0

調整。謝謝你的提示!我是新來的。 – 2011-04-10 04:38:05

回答

1

下次發佈完整代碼(全部刪除)。 op1op2是std :: string?您嘗試編寫op1op2中的字符,但尚未分配任何空間,即應在循環之前使用op1.resize(SOME_SIZE)或使用std::string::push_back將chars附加到操作數。

+0

啊,上面的那個人告訴我發佈我所有的代碼都很糟糕。這裏是完整的東西:http://pastebin.com/Q2fHV2pw我會嘗試,謝謝。 – 2011-04-10 04:49:30

+0

謝謝begemoth,工作!我只是不確定*爲什麼*它在一個簡單的任務上工作。但是,謝謝。我很感激! – 2011-04-10 04:56:56

+0

@Stefan,如果Begemoth回答了你的問題,那麼你可以將其標記爲真。因爲你的問題已經足夠大,需要花費一些時間,如果已經得到解答,這將是沒有用的。謝謝。 :) – iammilind 2011-04-10 05:40:38