使用sstream in在ofstream中提供输出文件的名称

Using sstream in to provide the name of output file in ofstream

本文关键字:文件 输出 in sstream ofstream 使用      更新时间:2023-10-16

我正在尝试使用sstream为ofstream中的文件提供名称。但是我得到了错误。

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main()
{
    stringstream ss;
    for(int i = 0; i < 3; i++) {ss<<"table"<<i;cout<<ss.str()<<endl;
        ofstream ofs(ss.str());
        ofs.close();
    }
}
错误:

temp2.cpp: In function ‘int main()’:
temp2.cpp:10:24: error: no matching function for call to ‘std::basic_ofstream<char>::basic_ofstream(std::basic_stringstream<char>::__string_type)’
temp2.cpp:10:24: note: candidates are:
/usr/include/c++/4.6/fstream:629:7: note: std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode]
/usr/include/c++/4.6/fstream:629:7: note:   no known conversion for argument 1 from ‘std::basic_stringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘const char*’
/usr/include/c++/4.6/fstream:614:7: note: std::basic_ofstream<_CharT, _Traits>::basic_ofstream() [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.6/fstream:614:7: note:   candidate expects 0 arguments, 1 provided
/usr/include/c++/4.6/fstream:588:11: note: std::basic_ofstream<char>::basic_ofstream(const std::basic_ofstream<char>&)
/usr/include/c++/4.6/fstream:588:11: note:   no known conversion for argument 1 from ‘std::basic_stringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘const std::basic_ofstream<char>&’

看起来您正在使用std::ofstream的前c++ 11实现:在原始的c++标准中,std::ofstream的构造函数(及其亲戚)没有构造函数取std::string。只有一个char const*的构造者。解决方法是从std::string:

中获取相应的C-string。
std::ofstream ofs(ss.str().c_str());

您不需要使用string,您可以使用:

ofs << ss.rdbuf();