我是C和C ++编程的新手,任何人都可以向我提示我在这里做错了什么。我正在尝试编写concat函数,该函数采用指向chars的指针并将第二个连接到第一个。代码确实可以做到这一点,但是问题在于它在末尾添加了一堆垃圾。例如,当传递参数-“ green”和“ blue”时,输出将是“ greenblue”加上一堆随机字符。我还编写了strcat使用的strlen函数,下面将提供该函数供参考。我在https://www.onlinegdb.com/online_c++_compiler使用在线编译器 确切的说明和规格是这样的:
strcat(char * __ s1,const char * __ s2)函数将__s2的内容连接到__s1,并以__s1的NULL字符开头。注意:串联包含__s2的NULL字符。该函数返回__s1。
int main(int argc, char** argv)
{
const int MAX = 100;
char s1[MAX];
char s2[MAX];
cout << "Enter your first string up to 99 characters. ";
cin.getline(s1, sizeof(s1));
int size_s1 = strlen(s1);
cout << "Length of first string is " << size_s1 << "\n";
cout << "Enter your second string up to 99 characters. ";
cin.getline(s2, sizeof(s2));
int size_s2 = strlen(s2);
cout << "Length of second string is " << size_s2 << "\n";
cout << " Now the first string will be concatenated with the second
string ";
char* a = strcat(s1,s2);
for(int i = 0; i<MAX; i++)
cout <<a[i];
// system("pause");
return 0;
}
//strcat function to contatenate two strings
char* strcat(char *__s1, const char *__s2)
{
int indexOfs1 = strlen(__s1);
int s2L = strlen(__s2);
cout <<s2L << "\n";
int indexOfs2 = 0;
do{
__s1[indexOfs1] = __s2[indexOfs2];
indexOfs1++;
indexOfs2++;
}while(indexOfs2 < s2L);
return __s1;
}
//Returns length of char array
size_t strlen(const char *__s)
{
int count = 0;
int i;
for (i = 0; __s[i] != '\0'; i++)
count++;
return (count) / sizeof(__s[0]);
}
答案 0 :(得分:2)
您看到的行为是__s1的空终止符被__s2的数据覆盖并且没有附加新的空终止符的结果。您看到的多余字符只是RAM中的随机值,恰好在字符串结尾之后。为防止这种情况,必须在字符串末尾添加NULL字符。
有效版本如下:
char* strcar(char *__s1, const char *__s2)
{
//check inputs for NULL
if(__s1 == NULL || __s2 == NULL)
return NULL;
int s1Length = strlen(__s1);
int s2Length = strlen(__s2);
//ensure strings do not overlap in memory
if(!(__s1 + s1Length < __s2 || __s2 + s2Length < __s1))
return NULL;
//append __s2 to __s1
//the "+ 1" here is necessary to copy the NULL from the end of __s2
for(int i = 0; i < s2Length + 1; i++)
result[s1Length + i] = __s2[i];
}
答案 1 :(得分:1)
您需要在__s1末尾添加尾随的“ \ 0”字符。
例如插入 __s1 [indexOfs1] = 0;
在返回行之前。