int main()
{
fstream file;
file.open("new_file.txt" , ios::app);
if (!file.is_open()){
cout << "File does not exist yet !\n";
return 1;
}
string input;
cout << "Add new line or edit? Write NEW or EDIT";
cin >> input;
if (input == "NEW")
{
add_new_info();
}
//.....
}
在另一个 cpp 中我有:
int add_new_info()
{
string aux;
int count;
cout << "Add line ID \n";
cin >> aux;
file << aux << "; ";
//...
}
基本上我想在 main
中打开 txt
文件,然后将其传递给 add_new_info()
。如何将 txt 文件
作为参数传递给另一个 .cpp
中的函数?
最佳答案
您可以只传递对打开文件的引用
int add_new_info(fstream& file)
{
// add info to the file
}
并在 main
中调用
add_new_info(file);
就像 zett42 在评论中提到的那样,如果该函数不使用任何特定于文件流的内容,则使用参数 std::ostream&
将允许将该函数用于其他类型的流同样,像 add_new_info(cout);
一样在控制台显示信息。
关于c++ - 如何将 .txt 文件作为参数传递给不同的 cpp 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160180/