2013-07-30 30 views
0

我需要創建一個基本的計算器,從文本文件中讀取。該文件的格式如下:文件輸入C++,其中行更改

2 
add 5 3 
sub_prev 1 
1 
mul 4 5 

的2代表操作的次數,明顯加入裝置,5 + 6,計算器會保持以前的結果,這樣就可以+ - * /它。這意味着有2個操作:添加5 + 3,然後從前一個結果中減去1。等等。

我有文件打開罰款,但無法弄清楚如何讓它正確讀取。 理想情況下,它會讀取第一個整數,輸入一個讀取正確的下列行數的循環,然後執行操作。在for循環完成第一個操作數後,它仍然處於讀while循環的文件中,但會重新進入for循環並讀取和計算更多操作。

示例代碼

while(myfile) // while reading the file 
{ 
    int PR = 0; //initialize the previous result as 0 
    myfile >> no; // grabbing the number of operations 
    cout << no << endl; // testing to see if it got it correct 

    for (int i = 1; i <= no; i++) // for the number of operations 
    { 
     myfile >> no >> op >> x >> y; // read the lines 
     if (op == "add") //there would be an if for each operation 
     { 
      PR = x + y; 
     } 
    } 

    myfile >> no >> op >> x >> y; 
} 

的問題是,它從來沒有想進入for循環,它讀取操作的沒有(數量爲2,但它通過while循環繼續,而不是去到for循環

**更新的代碼**

while(myfile) // while reading the file 
{ 
    int PR = 0; //initialize the previous result as 0 
    myfile >> no; // grabbing the number of operations 


    for (int i = 1; i <= no; i++) // for the number of operations 
    { 
    myfile >> op; 
    if (op == "add") 
    { 
    myfile >> x >> y; 
    PR = x + y; 
    }  

    if (op == "sub_prev") 
    { 
     myfile >> x; 
     PR = PR - x; 
    } 

    if (op == "mul") 
    { 
     myfile >> x >> y; 
     PR = x * y; 
     //cout << x << y << PR << endl; //testing mul operation 
    } 

    } 

    cout << "The result of operation " << " is " << PR << endl; 


} 

它正確地計算,但輸出錯誤:

Enter file name: newfile.txt 
The result of operation is 7 
The result of operation is 20 
The result of operation is 20 

RUN SUCCESSFUL (total time: 3s) 
+7

我們可以仔細研究任何代碼,以便我們確切知道您在做什麼?向我們展示你到目前爲止所擁有的。 –

+0

你怎麼知道它沒有進入?你如何檢查它?我不知道字符串的>>行爲,所以我可能會使用fscanf。 – wendelbsilva

+0

我已經在for循環中放了一個cout語句,它沒有輸出任何東西 –

回答

2

您正在修改no這裏

myfile >> no >> op >> x >> y; 

你不應該這樣做。我會建議像下面這樣的for循環體:

std::string operation; 
myfile >> operation; 
if (operation == "add") { 
    int a, b; 
    myfile >> a >> b; 
    PR = x + y; 
} else if (operation == "sub_prev") { 
    int value; 
    myfile >> value; 
    // do something 
} else { 
    // for other operations if added in future 
} 
+0

好吧,我認爲這是我需要去的軌道。基本上如何處理2個變量(添加等)與1(add_prev,sub_prev等)的線路 –

+0

因此,我的程序現在正在爲文件(7和20)正確計算值,但循環運行兩次第二個文件輸入,即使它只應運行一次。輸出操作次數證明值no更新爲1,但for循環仍然執行兩次。 –

+0

你可以發佈代碼嗎?將它添加到問題 –