C ++中的Concat字符串(STL)

时间:2009-06-11 07:56:27

标签: c++ string stl

我有这样的代码

string xml_path(conf("CONFIG"));

xml_path+=FILE_NAME;

其中, conf函数返回char *,文件名称为const char *

我想将它组合成一行,如

xml_path(conf("CONFIG")).append(FILE_NAME) 

我该怎么做?

任何建议??

4 个答案:

答案 0 :(得分:8)

问题要求一行:

string xml_path = string(conf("CONFIG")) + string(FILE_NAME);

(我假设xml_path是变量的名称,而不是我不知道的库中的某种调用。

答案 1 :(得分:4)

或者,如果要格式化不同类型的变量,请使用ostringstream。

例如。

std::ostringstream oss; 
int a = 2; 
char *s = "sometext"; 
oss<<s<<a<<endl; 
cout<<oss.str(); // will output "sometext2"

答案 2 :(得分:2)

const char * f = "foo";
char * b = "bar";

string s = string( f ) + b;

请注意,你不能使用append(-0,因为所有字符串都不是std:;字符串。如果你真的想要追加,那么它必须是两个阶段的过程:

string s ( f );
s.append( b );

答案 3 :(得分:0)

string xml_path(conf("CONFIG"));
xml_path += string(FILE_NAME);

应该这样做。