c++ - 如何将 .txt 文件作为参数传递给不同的 cpp 中的函数

标签 c++ arguments

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/

相关文章:

c++ - MergeSort 用于 double vector

python - 将 "-h"参数传递给子脚本

c++ - 如何强制编译器使用显式复制构造函数?

C++用抽象基类方法创建派生类

design-patterns - 处理命令行参数的设计模式是什么

.net - 当参数相互冲突时抛出什么最合适的异常?

c++ - 如何使用 std::allocator_traits::construct 从函数参数创建结构对象?

c++ - 在 C++ 中使用 getopt 时打印默认参数

c++ - c++ 可执行文件的不同 linux 发行版的问题

C++ 声明一个函数指针数组