通过引用其他函数传递.txt文件

时间:2013-12-31 12:03:58

标签: c++

我有以下代码,简单地读取前两行的.txt文件,它们应该指示.txt文件所携带的网格的高度和宽度。

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

void test(string filename, int& height, int& width);

int main(){
    string filename;
    ifstream infile;
    int height;
    int width;
    cout << "Enter filename: ";
    cin >> filename;
    test(filename, height, width);

    return 0;
}

void test(string filename,int& height, int& width){
    ifstream infile;
    infile.open(filename);
    infile >> height;
    infile >> width;
}

我想知道我是否可以更改test()的参数,以便将文件作为参数而不是文件名,因为我可能必须在其他地方使用.open(filename在其他功能,我不想一次又一次地输入它。如果可能的话,我知道它是,我只想在main中打开一次文件,并且能够在我的任何文件中用作参数。

1 个答案:

答案 0 :(得分:1)

您可以将文件传递给该函数。 你必须通过引用传递它。

void test(std::ifstream& infile, int& height, int& width) {
    infile >> height;
    infile >> width;
}

int main()
{
    std::string filename;

    std::cout << "Enter filename: ";
    std::cin >> filename;

    std::ifstream infile;
    int height;
    int width;
    infile.open(filename);
    test(infile, height, width);

    return 0;
}
相关问题