int to string conversion
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
char name[30];
sprintf(name, "%d-%d-%s", i, j, c);
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() );
}
}
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));
}}
精彩评论