Home > front end >  How I can fix this problem when print string in C?
How I can fix this problem when print string in C?

Time:11-01

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'. Anyone can help me. Thanks so much.

enter image description here

CodePudding user response:

For starters you are filling the character array s4.

for (i=p;i<strlen(s1);i  )
{
    s4[j]=s1[i];
    j  ;
}

But are outputting the character array 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.

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); 

CodePudding user response:

You have not declared s4 but you are using s4 instead of s3. And also printing s4.

s4[j]=s1[i];

Do this

s3[j] = s1[i];

Output:

s1: hello
s2: wo
Insert position: 3
s3: lo
  • Related