下面有一个程序,它只是将用户输入的字符串复制到另一个字符串中。该程序对某些输入工作正常,但对于大字符串的某些输入显示异常。我无法弄清楚。
#include<stdio.h>
int main()
{
int i, j;
char s1[100], s2[100];
printf("Enter a string : \n");
scanf("%[^\n]%*c", s1);
for(i=0; s1[i] != '\0'; i++)
{
s2[i] = s1[i];
}
printf("\n the original string is %s\n", s1);
printf("\n the string after copying is %s\n", s2);
return 0;
}
很少有输入实例: -
amitwebhero@AmitKali:~/c programs$ ./a.out
Enter a string :
hi there..!!
the original string is hi there..!!
the string after copying is hi there..!!
这里程序工作正常,但考虑到下面的情况,它在字符串的末尾添加了两个额外的垃圾值。
amitwebhero@AmitKali:~/c programs$ ./a.out
Enter a string :
my name is amit upadhyay
the original string is my name is amit upadhyay
the string after copying is my name is amit upadhyay�.�4
答案 0 :(得分:0)
#include <string.h>
int main( )
{
char source[ ] = "this is a string" ;
char target[20]= "" ;
strcpy ( target, source ); //strcpy( ) function copies contents of one string into another string.
printf ("\ntarget string = %s", target ) ;
return 0;
}