工作中有时候需要传入不定个数的字符串,就需要专门写一个函数动态添加字符串,下面看下函数:
#include#include#include "stdarg.h" std::string append(int count,const char* msg, ...){ std::string srcStr; va_list vaList; va_start(vaList, msg); char tmp[1024] = {0}; int n = 0; int true_count = count -1; strcat(tmp,msg); while(1) { strcat(tmp,"_"); strcat(tmp,va_arg(vaList,char*)); n++; if(n == true_count) { printf("%d\n",n); break; } } va_end(vaList);//结束可变参数列表 std::string stmp(tmp); srcStr += stmp; return srcStr; } int main(){ //string std::string str1 = "12"; std::string str2 = "34"; std::string str3 = "56"; std::string src = append(3,str1.c_str(),str2.c_str(),str3.c_str()); std::cout << src << std::endl; return 0; }
经测试好用。