传递具有void函数的结构

时间:2017-02-06 06:49:50

标签: c++ struct

我有结构:

const int strSize = 256;
const int databaseMaxSize = 10;

struct ComicInfo {
char name[strSize];
char author[strSize];
char volumeInfo[strSize];
char publisher[strSize];
int year;
double price;
int copies;
};

我如何将struct和databaseMaxSize传递给void函数,这是我要对结构做的所有事情吗?

编辑:完整代码,我知道我没有调用void函数。 我试图将7个变量放入void loadData函数中,如何创建正确的loadData函数并正确加载文本文件“Comics.txt”中的数据?

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>

using namespace std;

const int strSize = 256;
const int databaseMaxSize = 10; // Testing value, set it higher

struct ComicInfo {
char name[strSize];
char author[strSize];
char volumeInfo[strSize];
char publisher[strSize];
int year;
double price;
int copies;
};

void loadData(struct ComicInfo database[databaseMaxSize], int databaseSize);

int main () {
        ComicInfo database[databaseMaxSize];
        int databaseSize = 0;

        file.close();

        return 0;
}

void loadData(struct ComicInfo database[databaseMaxSize], int databaseSize)
{
        *databaseSize = 0;

        ifstream inputFile;
        inputFile.open("Comics.txt");

        if (!inputFile.is_open){
                exit(1);
        }

        inputFile.getline(database[name], databaseSize, ',');
        while (!inputFile.eof()){
                inputFile.getline(database[author], databaseSize, ',');
                inputFile.getline(database[volumeInfo], databaseSize, ',');
                inputFile.getline(database[publisher], databaseSize, ',');
                inputFile.getline(database[year], databaseSize, ',');
                inputFile.getline(database[price], databaseSize, ',');
                inputFile.getline(database[copies], databaseSize, ',');
                databaseSize++;
                inputFile.getline(database[name], databaseSize, ',');
                }
}

1 个答案:

答案 0 :(得分:1)

void my_function (struct ComicInfo& st, int databaseMaxSize) {
// code
}

请注意,我们正在传递对象的引用,以便不创建对象的额外副本。如果my_function不应该在struct数据中进行更改,则参数可以标记为const struct ComicInfo&

调用:

struct ComicInfo a;
my_function(a, databaseMaxSize); // Assuming you have databaseMaxSize available