使用字符串流在文件名中插入int
inserting int into file name using stringstream
我使用的是c++98(因为这是大学服务器上安装的)。我正在尝试将输出保存到文件中。文件名必须是dice_N.dat,其中N是骰子的掷数,我称之为N_trials。我试着遵循在文件名中插入int变量的建议。当使用第二个建议时,我得到了输出N.dat
ostringstream fileNameStream("dice_");
fileNameStream << n_trials << ".dat";
string fileName = fileNameStream.str();
ofstream myfile;
myfile.open(fileName.c_str());
我不能使用to_string
,因为这在c++98 中不受支持
使用:
ostringstream fileNameStream("dice_", std::ios_base::ate);
指定流打开模式为ate
请参阅此处
出现问题的原因是std::stringstream覆盖了初始缓冲区。
试试这个:
ostringstream fileNameStream; // let this be empty
fileNameStream << "dice_" << n_trials << ".dat"; // and pass "dice_" here
string fileName = fileNameStream.str();
ofstream myfile;
myfile.open(fileName.c_str());
或者,您可以使用std::ios::ate
作为标志创建ostringstream(ate
告诉它应该在输入的末尾附加的流(然后,您仍然可以在构造函数中传递"dice_"部分,它不会被覆盖)。
ostringstream ss;
ss << "dice_" << n << ".dat";
myfile.open(ss.str().c_str());
您可以使用std::to_string
从int
创建一个std::string
,然后进行连接
事实上,我只想把整个文件名做成
std::string fileName = "dice_" + std::to_string(n_trials) + ".dat";
只需使用<<
运算符提供所有三个部分,它也更可读,因为您不混合不同的语法:
ostringstream fileNameStream;
fileNameStream << "dice_" << n_trials << ".dat";
//...
使用boost:转换您的int
boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp
相关文章:
- C++ - 最坏情况和平均情况插入时间复杂度在 std::unordered_map <int,int>?
- 我正在尝试将 int 值插入字符串,而不是 1,我得到 10
- 如何在 std::map<const int、int> C++ 中重载插入运算符>>?
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 有没有办法通过插入新类型名称而不是 int 来使用 2 位大小类型而不是 int?
- 如何在'char'中转换和插入'int'以进行C++?
- c++:无法将 pair<int、MLine*> 插入到unordered_map
- 将int/char插入数据库
- Bool排序的插入函数,检查列表中是否已经存在int
- 插入到具有类型<int,矢量>的映射中<int>
- 在“std::map”中插入一个“int”值,该值应该存储“std::string”
- 在文件名中插入int变量
- 如何将元素插入 std::unordered_map<int, vector<Object*>>
- 插入 std::map<int, std::vector 的简短函数<int>>
- 为什么我的插入排序函数不会更改我从 int main 传递的数组
- 插入unordered_map<pair<int,int>, int> 抛出编译器错误
- 在 map<int 中插入,设置<int>>
- 将数据从两种不同的数据结构插入 std::map <std::string, int> mymap 并通过套接字发送
- 从文本文件中提取特定值(char & int)并插入到多个变量中C++
- 使用字符串流在文件名中插入int