流的std::无法将std::string写入文件

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

本文关键字:std 文件 string 流的      更新时间:2023-10-16

在发布之前的最后一次检查时已经解决了这个问题,但调试起来有点不好(至少对新手来说是这样),所以我无论如何都会发布它-可以随意删除。

问题是,在下面的标记行中,ofstream似乎无法写入一个简单的字符串;模板似乎是个问题:

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 */
    ...

这给出了错误:

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;// << ",";
             ^

因此,解决方案:缺少标头。

#include <iostream> 

已经在那里了,但没有

#include <fstream>