定义一个字符串 [英] Define a string
问题描述
我需要将字符串与字符和数字混合,但这些数字是可变的,例如;
char filename [] =" xxx"那么varxxx那么var;
即,filename =" ind23ept12"其中23是var x,12是var y。
int x;
int y;
char filename [20];
cin>> x>> y;
char * filename;
filename = strcpy(filename," inf_h_");
filename = itoa(filename,x);
filename = strcpy(filename," _f_");
filename = itoa(filename,y);
myfile.open(" filename");
I need to put a filename is mixed from characters and numbers but these numbers are variable, for example;
char filename[]="xxx" then var "xxx" then var;
i.e., filename="ind23ept12 " where 23 is var x and 12 is var y.
int x;
int y;
char filename[20];
cin>>x>>y;
char *filename;
filename=strcpy(filename,"inf_h_");
filename=itoa(filename,x);
filename=strcpy(filename,"_f_");
filename=itoa(filename,y);
myfile.open("filename");
推荐答案
我不知道它在C ++世界中是否运行良好,但对于C,你可以使用sprintf函数。格式与printf函数相同,只是第一个参数是您要写入的字符串。
I don''t know if it plays well in the C++ world, but for C you can use the sprintf function. The format would be the same as the printf function except that the first argument is the string you want to write to.
Sprintf应该在C ++中工作。只需包含c头文件。
C ++解决方案是使用一种叫做ostringstream的东西。它们存在于< sstream>中。头文件。你像cout一样使用它们,然后用str()提取字符串信息。例如:
ostringstream oss;
oss<< "路径" << 11<< " /文件" << 22.22;
cout<< oss.str()
将打印出path11 / file22.22
Sprintf should work in C++. Just include the c header file.
The C++ solution is to use something called an ostringstream. They are found in the <sstream> header file. You use them like cout and then extract the string info with str(). For example:
ostringstream oss;
oss << "path" << 11 << "/file" << 22.22;
cout << oss.str()
will print out "path11/file22.22"
当我尝试使用ostringstream oss时;
undecalare ostringstream
When I am trying to use ostringstream oss;
undecalare ostringstream
这篇关于定义一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!