Search code examples
c++stringofstream

std::ofstream not able to write std::string to file


Solved the problem already when checking a last time before posting this, but it looked somewhat evil to debug (at least for a newbie), so I'll post it anyway - feel free to delete.

The problem was that in the marked line below, ofstream seemed unable to write a simple string; the templating appeared to be the problem:

template <typename T>
void appendVectorToCSV(const std::string& header, std::vector<T> row,
        const std::string& outfilename){
    std::ofstream fout(outfilename);
    fout << header;// << ",";    /* The error line 80 */
    ...

This gives the error:

varUtils.hpp: In function ‘void appendVectorToCSV(std::string&, const std::vector<_RealType>&, const string&)’:
varUtils.hpp:80:10: error: no match for ‘operator<<’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘std::string {aka std::basic_string<char>}’)
     fout << header;// << ",";
          ^
varUtils.hpp:80:10: note: candidates are:
...
/usr/include/c++/4.8/complex:524:5: note: template<class _Tp, class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::complex<_Tp>&)
     operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x)
     ^
/usr/include/c++/4.8/complex:524:5: note:   template argument deduction/substitution failed:
...
varUtils.hpp:80:13: note:   ‘std::ofstream {aka std::basic_ofstream<char>}’ is not derived from ‘std::basic_ostream<_CharT, _Traits>’
     fout << header;// << ",";
             ^

Solution

  • So, solution: A missing header.

    #include <iostream> 
    

    was already there, but not

    #include <fstream>