我在使用返回字符的函数时遇到问题。这是函数的代码,它将 3 个字符(c1,c2,c3)收集到 1 个(infotot):
char gatherinfo(char *c1,char *c2,char *c3){
char infotot[256];
int n=sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
return *infotot;
}
在 main 中,我有这段代码来访问该函数:
char info[256];
*info=gatherinfo(c1,c2,c3);
其中 c1、c2 和 c3 定义为:
char *c1,*c2,*c3;
函数中,infotot取右值:
*infotot="c1;c2;c3;"
但是问题出在main,这里的info取值如下;
*info="lÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ"
其中首字母“l”对应c1的首字母。我该如何解决才能获得 info="c1;c2;c3;"?
最佳答案
gatherinfo
返回单个字符,而不是字符串。您将该字符分配给数组 info
的第一个元素。
这个数组不是空终止的,所以当你打印它时,你会看到第一个元素后跟垃圾。
您必须返回一个 std::string
。可以复制 std::string。
std::string gatherinfo(char *c1,char *c2,char *c3){
char infotot[256];
sprintf(infotot,"%s;%s;%s;",c1,c2,c3);
return infotot; // Here infotot is used to construct the std::string returned by the function. Same as return std::string(infotot);
}
您还可以使用 std::string 运算符 +(串联)
std::string gatherinfo(char *c1,char *c2,char *c3){
return std::string(c1) + ";" + c2 + ";" + c3 + ";";
}
关于c++ - 从函数返回的错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36355179/