我有一个学校项目。该项目要求我编写一个名为 openFiles 的函数。所以我需要在函数内部打开一个文件并在 main 或其他函数中使用它。我怎样才能做到这一点?假设我的文件名为“1”
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void openFiles(string);
main() {
openFiles("1");
string str;
while(file>>str)cout<<str;
}
void openFiles(string str){
fstream file;
file.open(str);
}
最佳答案
因为fstream
有一个move constructor ,您可以将 fstream
对象作为 openFiles
的结果返回,如下所示:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
fstream openFiles(string);
int main() {
auto file = openFiles("1");
string str;
while(file>>str)cout<<str;
}
fstream openFiles(string str){
fstream file;
file.open(str);
return file;
}
当然,你应该检查打开是否成功。
关于c++ - 在函数中打开文件并在 main 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65190240/