我需要創建一個基本的計算器,從文本文件中讀取。該文件的格式如下:文件輸入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)
我們可以仔細研究任何代碼,以便我們確切知道您在做什麼?向我們展示你到目前爲止所擁有的。 –
你怎麼知道它沒有進入?你如何檢查它?我不知道字符串的>>行爲,所以我可能會使用fscanf。 – wendelbsilva
我已經在for循環中放了一個cout語句,它沒有輸出任何東西 –