首页 文章

QT ofstream使用变量作为路径名

提问于
浏览
1

我正在尝试创建一个需要QString和int的函数 . 将QString变量转换为ofstream的文件名,然后取整数并将其放入文件中 . 到目前为止,我已设法获取一个常量文件名,如“Filename.dat”,并将变量写入其中 . 但是当我尝试使用QString时:

void write(const char what,int a){
    std::ofstream writefile;
    writefile.open("bin\\" + what);
    writefile << a;
    writefile.close();
}

我收到一个错误

void write(const char,int)': cannot convert argument 1 from 'const char [5]' to 'const char

这是调用write()的函数;

void Server::on_dial_valueChanged(int value)
{
    write("dial.dat",value);
}

当我使用“bin \ dial.dat”而不是将“bin”与字符串组合时,它可以正常工作 . ofstream.open();使用“const char *” .

我已经尝试了所有的文件类型,因此它们可能与我的描述不符

The question is- 有没有人知道如何组合"bin"和QString并使其与ofstream一起使用?我让它发挥作用 . 谢谢!任何建议都非常受欢迎

1 回答

  • 1

    void write(const char what,int a) 错误,因为您只传递一个char函数,您应该 void write(const char* what,int a) 将指针传递给cstring开头 .

    你也想连接两个cstrings,在c中你不能像在其他语言中一样,但你可以使用std :: string来做你想要的 .

    试试这个

    #include <string>
    
    void write(const char* what,int a){
        std::ofstream writefile;
        std::string fileName("bin\\");
        fileName+=what;
        writefile.open(fileName.c_str());
        writefile << a;
        writefile.close();
    }
    

相关问题