C++ 流不';当变量是属性时不起作用

C++ 流不';当变量是属性时不起作用,c++,ofstream,C++,Ofstream,本流程工程的实施: bool LinuxSysCall::addNewUser(std::string const &login, std::string const &password) { std::ofstream out; out.open(DATABASEPATH, std::ios::app); if (out.is_open()) { std::string str = login + ":" + password

本流程工程的实施:

bool LinuxSysCall::addNewUser(std::string const &login, std::string const &password) {

    std::ofstream out;
    out.open(DATABASEPATH, std::ios::app);

    if (out.is_open())
    {
        std::string str = login + ":" + password + "\n";
        std::cout << "writing " << str << std::endl;
        out << str;
        return true;
    }
    return false;
}
//The new line is written in the file

为什么?

std::ofstream的析构函数调用
close
。这会将文本刷新到文件中

如果要使用成员变量(而不是“属性”),则需要:

bool LinuxSysCall::addNewUser(std::string const &login, 
                              std::string const &password) {
    this->out.open(DATABASEPATH, std::ios::app);

    if (this->out.is_open())
    {
        std::string str = login + ":" + password + "\n";
        std::cout << "writing " << str << std::endl;
        this->out << str;
        this->out.close();
        return true;
    }
    return false;
}
bool LinuxSysCall::addNewUser(std::string const&login,
std::字符串常量和密码){
这个->out.open(DATABASEPATH,std::ios::app);
如果(此->out.is_open())
{
std::string str=login+“:”+密码+“\n”;

std::cout在调用
open(…)
之前,流
out
处于什么状态?可能是这个->out.is\u open()返回false。在不需要它的时候,请不要使用
这个->
。它很吵,让你看起来像个C程序员。
bool LinuxSysCall::addNewUser(std::string const &login, 
                              std::string const &password) {
    this->out.open(DATABASEPATH, std::ios::app);

    if (this->out.is_open())
    {
        std::string str = login + ":" + password + "\n";
        std::cout << "writing " << str << std::endl;
        this->out << str;
        this->out.close();
        return true;
    }
    return false;
}
    this->out << std::flush;