0

在 C++ 中,为了编辑许多文件,我使用一些类似于

#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;

int main(){
    char nombre[10];
    int i;
    ofstream salida;

    for (i = 10; i < 20; i++) {
        sprintf(nombre,"archivo%d.txt",i);
        cout << nombre<<endl;
        salida.open(nombre);
        salida << 1000*i << endl;
        salida.close();
    }
    return 0;
}

存在更好的 C++ 方式吗?没用的char[10]

4

3 回答 3

2

您可以使用 C++std::ostringstream类型:

for (int i = 10; i < 20; i++) {
    std::ostringstream filename;
    filename << "archivo" << i << ".txt";
    salida.open(filename.str().c_str());
       /* ... */
    salida.close();
}

的大部分用途sprintf可以替换为std::ostringstream. 不过,您需要包含<sstream>头文件才能使其正常工作。

希望这可以帮助!

于 2012-05-15T23:37:02.903 回答
2

我认为您只是在寻找 c++ 字符串类。

它可以在std::string.

这是一个很好的参考

在这里,您将使用字符串:

#include <sstream>

...{ 
    std::string fileName = "archivo";
    std::string extension = ".txt";

    ...

    salida.open((fileName + NumberToString(i) + extension).c_str()); 

    ...
}

template <typename T>
string NumberToString ( T Number )
{
    stringstream ss;
    ss << Number;
    return ss.str();
}

以上是这里推荐的。

于 2012-05-15T23:39:38.450 回答
0

boost::format将非常方便地替换 sprintf。如果这是您正在寻找的。

于 2012-05-15T23:36:30.457 回答