gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:11:49 24 4
gpt4 key购买 nike

我有以下代码,前两行简单地读取 .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;
}

关于c++ - 通过引用其他函数传递 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com