[英]How I can fix this problem when print string in C?
I have problem with my code.我的代码有问题。
#include <stdio.h>
#include <string.h>
#define size 100
int main()
{
char s1[size],s2[size],s3[size];
int i,j,k,p;
printf("s1: ");fgets(s1,size,stdin);
printf("s2: ");fgets(s2,size,stdin);
if (s1[strlen(s1)-1]=='\n')
s1[strlen(s1)-1]='\0';
if (s2[strlen(s1)-1]=='\n')
s2[strlen(s2)-1]='\0';
printf("Insert position: ");scanf("%d",&p);
j=0;
for (i=p;i<strlen(s1);i++)
{
s4[j]=s1[i];
j++;
}
printf("s3: %s\n", s3);
}
When I run this file.当我运行这个文件时。 This have wrong result.这有错误的结果。 I don't know why s3 is 'a'.我不知道为什么 s3 是“a”。 Anyone can help me.任何人都可以帮助我。 Thanks so much.非常感谢。
For starters you are filling the character array s4
.对于初学者,您正在填充字符数组s4
。
for (i=p;i<strlen(s1);i++)
{
s4[j]=s1[i];
j++;
}
But are outputting the character array s3
但是正在输出字符数组s3
printf("s3: %s\n", s3);
that as and the array s4
does not contain a string.:) The array s3
is not initialized and contains indeterminate values. as 和数组s4
不包含字符串。:) 数组s3
未初始化并包含不确定的值。
You need to write at least like你至少需要这样写
j=0;
for ( size_t n = strlen( s1 ); i < n; i++ )
{
s3[j]=s1[i];
j++;
}
s3[j] = '\0';
printf("s3: %s\n", s3);
You have not declared s4 but you are using s4 instead of s3.您尚未声明 s4,但您使用的是 s4 而不是 s3。 And also printing s4.并且还打印 s4。
s4[j]=s1[i];
Do this做这个
s3[j] = s1[i];
Output:输出:
s1: hello
s2: wo
Insert position: 3
s3: lo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.