2017-10-09 82 views
0

您好im學習c + +和我想知道如何我可以調用將寫入文件的函數。在該功能中,它將調用其他功能並打印輸出。我會怎麼做?如何調用函數,將寫入文件,並在該函數內調用其他函數

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

void buildArray(float arrayScores[], int numOfScores); 
void printOutArray(float arrayScores[], int numOfScores); 
void writeToFile(float arrayScores[], int numOfScores); 

int main(){ 

    int numOfScores; 
    cout << "Enter the number of scores: " 
    cin >> numOfScores; 

    float *arrayScores = nullptr; 
    arrayScores = new float [numOfScores]; 
    writeToFile(arrayScores, numOfScores); 
    delete [] arrayScores; 
} 

void buildArray(float arrayScores[], int numOfScores){ 
    float score = 0; 
    for (int i=0; i<numOfScores; i++){ 
    cout << "Enter the score: "; 
    cin >> score; 
    arrayScores[i] = score; 
} 

void printOutArray(float arrayScores[], int numOfScores){ 
    int Items = numOfScores; 
    for (int i = 0; i<numOfScores; i++){ 
     float grade = arrayScores[i]; 
     cout << "Score number " << i+1 << ": " << arrayScores[i] << endl; 
    } 

} 

void writeToFile(arrayScores[], int numOfScores){ 
    ofstream outfile; 
    outfile.open("Scores.txt"); 
    outfile << buildArray(arrayScores,numOfScores); 
    outfile << printOutArray(arrayScores,numOfScores); 
    outfile.close(); 
} 
+0

'functionThatCallsOtherFunctionsInOrderToPrintToAFile();' - 但是你應該考慮一個更短,更具體的域名。 – StoryTeller

+0

如果你使用新的,請正確使用它。你錯過了刪除。 – deviantfan

+0

那麼除非你詢問構建錯誤,那麼請向我們展示*構建*的代碼。我建議你花些時間[閱讀如何提出好問題](http://stackoverflow.com/help/how-to-ask),並學習如何創建[最小,完整和可驗證示例]( http://stackoverflow.com/help/mcve)。 –

回答

0
outfile << buildArray(arrayScore, numOfScores); 

嘗試發送由buildArray返回outfile值。但是你已經聲明buildArray不會返回任何東西!您已通過在其聲明(和定義)中的名稱前寫入void來完成此操作。

你有兩個選擇

  1. 回報什麼,那就是你要打印,爲buildArray結果。
  2. 代替發送結果buildArrayoutfile的,通outfile作爲參數傳遞給buildArray和發送日期outfilebuildArray體內。

下面是一些代碼,讓你用第二個想法去。

#include <ostream> 

void buildArray(std::ostream& outfile, float arrayScores[], int numOfScores){ 
    float score = 0; 
    for (int i=0; i<numOfScores; i++){ 
    cout << "Enter the score: "; 
    cin >> score; 
    arrayScores[i] = score; 
    outfile << /* whatever you want to write goes here */ 
} 

注意要點:

  1. 包含了ostream頭。
  2. 爲函數添加一個參數,用於要使用的文件流。
  3. 使用函數內部的流,顯示在主體的最後一行。