views:

108

answers:

3

I would like to save files with different names in a loop. I use a library that needs a char as a parameter of the file...

for(int i=0;i<nodes;i++){
for(int j=0;j<nodes;j++){
    char a[20]="test";
    char c[20]="xout.dat";
Lib::SaveFile(_T(a), _T(c));
}}

The above code works, but I would like to change the name of the xout.mid to the corresponding integer so I would get i*j files with different names.i and j go from 0 to about 30.

I would like to get a char with the name i_j_xout.dat

+3  A: 
char name[30];
sprintf(name, "%d-%d-%s", i, j, c);
Sjoerd
Oh Thanks... I guess this is textbook example number 2 after "hello world", Had some problems with the difference with char and string..
mrbuxley
I know that on current architectures the, erm, "chance" of overflowing `name` is marginal, but I think that, in general, using `sprintf()` warrants a warning.
sbi
Hi, generally try not to use `[f/s]printf` family of functions in C++. When you have buffer overflow problems caused by them your application crashes in different places and the problem is difficult to track. The code above will not generate a crash, but still, it's good practice to use safe code instead (`std::o[f/string]stream` family of classes).
utnapistim
A: 

Use sprintf() function:

for(int i=0;i<nodes;i++){
for(int j=0;j<nodes;j++){
    char c[20];
    char a[20]="test";
    sprintf(c, "%d_%d_xout.dat", i, j );
Lib::SaveFile(_T(a), _T(c));
}}
PeterK
Why is `c` allocated dynamically? I don't know `Lib::SaveFile()`, but if it throws, then this leaks. Using an automatic variable would avoid that.
sbi
Edited, thanks.
PeterK
+2  A: 

Instead of using char buffers and sprintf, consider using std::string and std::ostringstream:

#include <sstream>
#include <string>

[...]

std::basic_string<TCHAR> nameA = _T("test");
std::basic_ostringstream<TCHAR> nameC;
for(int i=0;i<nodes;i++){
    for(int j=0;j<nodes;j++){
        nameC.str(_T(""));
        nameC << i << "_" << j << "_xout.dat";
        Lib::SaveFile( nameA.c_str(), nameC.str().c_str() );
    }
}
utnapistim