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

Passing .txt files by reference to other functions

本文关键字:txt 文件 函数 引用 其他      更新时间:2023-10-16

我有以下代码,它简单地读取前两行的.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中打开文件一次,并能够在我的任何文件中用作参数。

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

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;
}