使用字符串流在文件名中插入int

inserting int into file name using stringstream

本文关键字:插入 int 文件名 字符串      更新时间:2023-10-16

我使用的是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_stringint创建一个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