2015-10-13 25 views
-1

我的項目是用一組整數(我不知道有多少)讀取一個輸入文件,計算這些整數的總和,然後創建一個輸出文件並寫入總數輸出文件。C++試圖從輸入文件中計算總數

我的代碼中的所有東西都有效,除了我從輸出文件得到的總數實際上並不是我試圖計算的總數。

例如,包含在我的testfile1文件的整數是:14,9,12,-6,-30,8,109

我讓我的總和文件讀取數28,其顯然不是這些整數的總和。

這是我的代碼。我知道一些部分是多餘的,或者不像C++那麼簡單,但是我試圖根據我迄今爲止從我的教科書中瞭解到的內容對其進行格式化,所以有些部分可能不會那麼先進。某些行號因爲我拿出說明塊而丟失。 我真的只需要弄清楚爲什麼總沒有正確添加(行33-38)。任何幫助將不勝感激。

非常感謝大家的進步!

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

int main() { 

    ifstream inputFile; 
    ofstream outputFile; 
    string testfile1; 
    string sum; 
    int total=0; 
    int num; 

    cout << "Please input name of file." << endl; 
    getline (cin, testfile1); 

    inputFile.open(testfile1.c_str()); 

    if(inputFile) { 
     while(inputFile >> num){ 
     total=+num; 
     } 
     inputFile.close(); 
    } 
    else { 
     cout << "could not access testfile1" << endl; 
    } 
    outputFile.open("sum"); 

    if(outputFile) { 
     outputFile << total << endl; 
     outputFile.close(); 
    } 
    else { 
     cout << "could not access file." << endl; 
    } 

    return 0; 
} 
+2

你有沒有試着寫讀,你去的數字? –

+0

令人驚訝的是你得到28,而不是109. – Evert

+0

謝謝你的建議。試過之後,我仍然得到錯誤的總數。 –

回答

3

Typo。

使用

total += num; // Need to use += 

,而不是

total=+num; // Not =+. 
+0

修復它。非常感謝! –