我写了这段代码,但它没有用。它最终会显示一些额外的字符。这是代码:
// Program to concate/join two string
#include<stdio.h>
#include<string.h>
main()
{
int i,j,n=0;
char str[100],str2[100],str3[100];
printf("Enter string 1:\n");
gets(str);
printf("Enter string 2:\n");
gets(str2);
for(i=0;str[i]!='\0';i++)
{
str3[i]=str[i];
n=n+1;
}
for(i=0,j=n;str2[i]!='\0';i++,j++)
{
str3[j]=str2[i];
}
printf("The concanted sring is: \n");
puts(str3);
}
完成复制循环后,使用str3
终止'\0'
字符串:
for(i=0,j=n;str2[i]!='\0';i++,j++)
{
str3[j]=str2[i];
}
str3[j] = '\0'; // proper termination of the `str3`.
否则str3
将继续,直到遇到内存中的第一个随机'\0'
。这就是为什么当你打印str3
时你得到额外的字符。
另请阅读:gets() function in C和
Why is the gets function so dangerous that it should not be used?
在你的程序中避免使用gets()
!
在C语言中,字符串是以空字符结尾的字符数组。
它最终会显示一些额外的字符。
这样做的原因是,在将str3
连接到字符串之后,您不会在字符串str2
的末尾添加空字符。在连接字符串的末尾添加一个空字符,如下所示:
str3[j] = '\0';
另外,你应该not use gets()
。它已经过时了。相反,使用fgets()
。
额外:
遵循良好的编程习惯,养成将int
指定为main
函数的返回类型的习惯。
您可以使用最佳字符串操作函数“strcat()”之一轻松地连接到字符串。尝试使用以下解决方案
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello" , str2[] = "There";
//concatenates str1 and str2 and resultant string is stored in str1.
strcat(str1,str2);
puts(str1);
puts(str2);
return 0;
}
输出:HelloThere
那里