C++中的文件命名

File naming in C++

我用 c++ 编写了一个程序,运行 是一个循环。每当循环结束时,矩阵的值,比如 A[i][j],都会使用数值方法进行更改。

我通常做的是使用 if-elseswitch 语句在特定循环计数器输出 A 的最新值if-else 语句中提到的文件。但是,如果我想在每个循环计数器中获取矩阵值,我该怎么做?

我无法写出所有条件。 请帮助,或者更好,如果可能的话,提供一个伪代码,以便 1 文件名的循环计数器值(假设 i)是 1.txt1.dat),并且对于i=2 文件名为 2.dat 依此类推。

我已经添加了我想要的示例代码。

int main()
{
    string str="";
    int a[10];
    for(int i=0;i<10;i++)
    {
        a[i]=i;
    }

    for(int t=1;t<16;t++)
    {
          str=t;
          ofstream data("str.dat");
          if(data.is_open())
          {
              cout << "File Opened successfully!!!. Writing data from array to file" << endl;
              for(int i=0;i<10;i++)
              {
                  data<<a[i]<<endl;
              }
          }
          else //file didn't open
          {
              cout << "File could not be opened." << endl;
          }

          for(int m=0;m<10;m++)
          {
              a[m]=2*a[m];
          }

    }

    return 0;
}

在这段代码中,我得到的只是一个名为 str.dat 的文件。我希望它是 1.dat、2.dat、3.dat 等,通过将 t 的值传递给字符串 str 然后让文件 t 的次数为 运行.

我希望这有助于理解问题。

我相信您正在寻找这个:

#include <sstream>

// ...

std::ostringstream filename;
filename << "File-" << i << ".dat";
std::ofstream file(filename.str().c_str());

这使用字符串流(输出到字符串)从固定文本和 i 的值构造文件名。然后,使用其成员函数.str()从字符串流中提取构造的字符串,并将其作为参数传递给文件输出流的构造函数。这意味着它将打开相应的文件。

就这么简单:

for( int i = 0; i < someValue; ++i ) {
    std::string filename = std::to_string( i ) + ".txt";
    ...
}

感谢所有帮助.....终于得到它(在一些帮助下).....我把它粘贴在这里以防将来有人需要它......

int main()
{
    int a[10];
    for(int i=0;i<10;i++)
    {
        a[i]=i;
    }

    for(int t=1;t<15;t++)
    {
          string name="";
          name+=to_string(t);
          ofstream data(name.c_str());
          if(data.is_open())
          {
              cout << "File Opened successfully!!!. Writing data from array to file" << endl;
              for(int i=0;i<10;i++)
              {
                  data<<a[i]<<endl;
              }
          }
          else //file didn't open
          {
              cout << "File could not be opened." << endl;
          }

          for(int m=0;m<10;m++)
          {
              a[m]=2*a[m];
          }

    }

    return 0;
}