使用sstream in在ofstream中提供输出文件的名称
Using sstream in to provide the name of output file in ofstream
我正在尝试使用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
:
std::ofstream ofs(ss.str().c_str());
您不需要使用string
,您可以使用:
ofs << ss.rdbuf();
相关文章:
- 如何在 的开头<x>和结尾<y>之间更改带有文件输出的字符串的值
- C++对象数组的文件输出
- bcdedit 文件输出不起作用,但其他命令可以
- 如何从文本文件输出数据?(学生成绩单计划)
- 使用 C++文件 I/O 输出 pdf 文件
- C 文件输出垃圾
- 从堆栈中读取字符后,如何修复不正确的文件输出
- C++:具有随机名称的文件输出
- 在命令提示符下看到换行符,但在文件输出中可以看到 相同的字符串
- 生成文件不会生成预期的文件输出
- C++11 fgetc 在"r+b"模式下使用时向我的文件输出 0
- 使用函数从文件输出
- GCC.obj文件输出不具有确定性(.debug_info,PROGPITS部分)
- C cstdiofile :: Writestring给出了不正确的文件输出
- C 输出:STD :: COUT和文件输出没有相同的内容
- GCC和MSVC之间的文件输出不一致
- C++文件输出奇怪的数字,并且部分代码没有运行
- 如何将特定字符从TXT文件输出到特定点
- C 调用从TXT文件输出信息的函数
- 将交易从文本文件输出到屏幕