Search code examples
c++stringcsvofstreamqstring

ofstream writing data to file: How do I pass a previously defined string as the filename


I have a program that I have written with C++, OpenCV and Qt, where I am trying to write data to a csv file. In my Qt Widget I have created a QFileDialog that allows me to choose where to save the csv file.

This path is then stored as a QString, and converted to a std::string as follows;

std::string OutputFileName = OutputFile.toUtf8().constData();

I then try to pass this std::string to my ofstream::open function as follows:

ofstream CSVFile;
CSVFile.open(OutputFileName);

And there lies the problem; it refuses to compile, giving the error

no matching function for call to 'std::basic_ofstream >::open(std::string&)'

I'm very new to programming and thus I have no idea what exactly the problem is here. I have tried looking at this, but from what I can tell that is a Windows specific solution, and I am using OSX.

Can anyone tell me how I can successfully pass the filepath stored in the QString to the CSVFile.open() term?


Solution

  • in C++03, ofstream::open takes const char* parameter.

    If OutputFileName is std::string.

    Try:

    CSVFile.open(OutputFileName.c_str());
    

    If outputFileName is Qstring

    CSVFile.open(OutputFileName.toStdString().c_str());
    

    See QString::toStdString reference