如何调用将写入文件并在该函数内调用其他函数的函数

时间:2017-10-09 06:02:22

标签: c++

您好我正在学习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();
}

1 个答案:

答案 0 :(得分:0)

outfile << buildArray(arrayScore, numOfScores);

尝试将buildArray 返回的值发送到outfile。但是您已声明buildArray 不会返回任何内容!您已通过在其声明(和定义)中的名称前面编写void来完成此操作。

您有两个选择

  1. 作为buildArray
  2. 的结果,返回您要打印的内容
  3. 不是将buildArray结果发送到outfile,而是将outfile作为参数传递给buildArray,并将日期发送到{{1}在outfile的主体内部。
  4. 以下是一些代码,可以帮助您了解第二个想法。

    buildArray

    注意事项:

    1. 包含#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 */ } 标题。
    2. 为您要使用的文件流添加一个参数给函数。
    3. 使用函数内部的流,显示在正文的最后一行。