我想知道为什么 char 数组的显示是短的几个字符。但是,当我使用 length+2 时,会显示所有字符。我不确定我做错了什么。您的帮助将不胜感激。我正在使用 Dev-C++
#include <iostream>
#include <string.h>
using namespace std;
char *Appendstring(char *a, char *b, char *c, char *d, char *e) // will append b to the end of a
{
// char *buffer = new char[strlen(a)+strlen(b)+1];
static char buffer[90];
char *p=buffer;
while(*p++=*a++); // Copy a into buffer
while(*p++=*b++); // Copy b into buffer right after a
while(*p++=*c++); // Copy c into buffer right after b
while(*p++=*d++); // Copy d into buffer right after c
while(*p++=*e++); // Copy e into buffer right after d
*p=0; // Null-terminate the string
return buffer;
}
int main ()
{
char *new_string;
int length;
char *str="Because";
char *add="it has been";
char *addstr1="very warm";
char *addstr2="lately";
char *addstr3="Summer is coming!";
length=strlen(str)+strlen(add)+strlen(addstr1)+strlen(addstr2)+strlen(addstr3)+1; //total length of the new string
new_string=Appendstring(str, add, addstr1, addstr2, addstr3);
for (int i=0; i<=length+2; i++) //Why do I need to do length+2 to have all characters displayed???
cout<<new_string[i];
return 0;
}