Alan os Alan os - 19 days ago 5
C++ Question

QT ofstream use variable as a path name

I'm trying to make a function which takes QString as well as an int.
Convert QString variable into a filename for ofstream, then take the integer and place it into the file. So far I have managed to take a constant filename such as "Filename.dat" and write a variable into it. However when I try to use QString like this :

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


I get an error

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


This is the function which calls write();

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


When I use "bin\dial.dat" instead of combining "bin\" with a string it works fine. ofstream.open(); uses "const char*".

I've tried all the filetypes so they may not match my description

The question is-
Does anybody have an idea how to combine "bin\" and a QString and make it work with ofstream?
I've spend a lot of time googling it but still can't make it work.
Thanks!
Any suggestions are more than welcome

Answer

void write(const char what,int a) is wrong as you pass only one char to function you should have void write(const char* what,int a) to pass pointer to cstring beginning.

You also want to concat two cstrings and in c++ you can't do it like in other languages but you can use std::string to do what you want.

Try this

#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();
}
Comments