无法连接2个以上的字符串

时间:2012-04-30 13:50:26

标签: c++ arrays char

我写了一个有两个参数的函数,因此可以连接2个字符串数组。但是,我需要使用相同的函数来连接五个参数。这就是我被卡住的地方,因为我的功能无法正常工作。我只保留最后一个附加物。我贴了下面的代码。我们将不胜感激。我用C ++编写代码,我使用的是dev-C ++。

#include<iostream>
#include<conio.h>


using namespace std;


char *Append(char *str, char *add)
{
 int m=5;
 static char buffer[150];  
 char *p=buffer;
 while(*p++=*str++);
 p--;
 while(*p++=*add++);  

 return buffer;  

}

int main()
{
 static char *buffer1;
 char *temp=" "; 
 char *str="Be, ";
 char *add="or not to be, ";
 char *str3="that's the question ";
 char *str4="Whether 'tis Nobler in the mind to suffer ";
 char *str5="The Slings and Arrows of outrageous Fortune,";

 buffer1=Append(str, add);
 cout<<buffer1;
 ///while(*temp++=*buffer1++);//where the problem starts!  
 /// temp--;
 Append(temp, str);    ///i am trying to append all strings into temp!!
 buffer1=Append (temp, add);
 cout<<endl<<buffer1;


 getch();
 return 0;
}

2 个答案:

答案 0 :(得分:4)

您正在将连接的字符串写入静态缓冲区(static char buffer[150];)。每次调用append函数时,都会写入相同的缓冲区,这意味着您将覆盖上一次调用所创建的字符串以进行追加。

 buffer1=Append(str, add); // buffer1 contains "Be, or not to be, "
 Append(temp, str); // buffer1 now contains " Be, " even though you don't assign the result of Append to buffer1

但是,如果你这样做,你仍然可以使用它:

buffer1=Append(str, add);
Append(buffer1, str3);
Append(buffer1, str4);
Append(buffer1, str5);

虽然你必须小心不要超出你的缓冲区。

这是有效的,因为当你将buffer1作为第一个字符串传递时,append函数的第一步就是将先前连接的字符串复制到自身中,第二步是添加新的字符串。

答案 1 :(得分:1)

你的问题对我来说并不完全清楚。假设您希望多次使用Append()来连接连续的5个字符串,请使用main()这样。

int main()
 {
 static char *buffer1;
 char *temp=" "; 
 char *str="Be, ";
 char *add="or not to be, ";
 char *str3="that's the question ";
 char *str4="Whether 'tis Nobler in the mind to suffer ";
 char *str5="The Slings and Arrows of outrageous Fortune,";

 buffer1=Append(str, add);
 cout<<buffer1;
 ///while(*temp++=*buffer1++);//where the problem starts!  
 /// temp--;
 buffer1=Append(buffer1, str3);    ///i am trying to append all strings into temp!!
 buffer1=Append(buffer1,str4);
 buffer1=Append(buffer1,str5);
 cout<<endl<<buffer1;


 getch();
return 0;
}
相关问题