C++ 为什么在一种情况下保存到文件有效而另一种情况无效?

标签 c++

这里需要一些帮助,有人可以向我解释为什么这是有效的吗:

void change_boss()
    {
        string password;
        fstream file;



        cout << "Type new password" << endl;
        cin >> password;
        file.open("admin_list.txt");
        file << password;
        file.close();

    };

这行不通吗?

void change_worker()
    {
        string pass;
        fstream file;


        cout << "Type new password" << endl;
        cin >> pass;
        file.open("worker_list.txt");
        file >> pass;
        file.close();

    };

有什么想法吗?因为我不知道那有什么问题

最佳答案

您使用了错误的运算符;你的第二个 block 应该替换这个:

file >> pass;

与:

file << pass;

如果您不需要同时读取和写入文件,请考虑使用std::ifstreamstd::ofstream 分别用于只读和只写操作。

关于C++ 为什么在一种情况下保存到文件有效而另一种情况无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755677/

相关文章:

c++ - CGAL Polyhedron_3 flip_edge 函数打破表面

c++ - 我将如何使用 getopt 呢?

c++ - 如何在 OpenGL 中将像素绘制为多边形的纹理?

c++ - 了解低级鼠标和键盘钩子(Hook)(win32)

c++ - 如何跟踪单链表的开头?

c++ - 我的字符串比较在 Cpp 中不起作用

c++ - 使用 GLM 的最佳 glMatrixMode() 是什么?

C++ pow函数-无效结果?

c++ - char (*)[] 转换的 vector

c++ - 同一个库在16.04下和14.04下定义了不同的符号