raylyn
raylyn

Reputation: 63

Inputting a string and copying its value to a second string gives incorrect results in c

In this program, i am trying to read a string str from the standard input stdin using the function fgets, copy it into another string called copy, and then display the copied string and its size.

int main(){
  char str[10];
  char copy[10];

  printf("length of str: %ld \n" ,strlen(str));
  puts("enter characters:");
    
  fgets(str,strlen(str), stdin);
  strcpy(copy,str);
  
  printf("the copy string: ");
  puts(copy);
  printf("after copy: the size - %zu \n",strlen(copy));
}

But when i run it with a test string ,for example randomString, i get

length of str: 2 
enter characters:
randomString
the copy string: r
after copy: the size - 1 

I don't understand why in the beginning it shows the length of the original string str as 2 or why only the first character of the inputted string is copied to the second string.What changes should be made to the program so that it successfully copies the inputted string to string copy?

Upvotes: 0

Views: 43

Answers (1)

Juan
Juan

Reputation: 54

The problem comes from the fact that str is not initializated by the ti,e you first try to use it. strlen() counts all the characters present in the array before the null termination. In you example, str clearly contains a couple of random characters followed by a 0.

On the other side, fgets() takes as argument the number of character to be read, includind the null character at the end of a string. This means that, if your str contains two random characters before the null character, strlen() return 2 and your fgets() can only read 1 character total.

To fix this, just change strlen() by sizeof() to obtain the size of the array containing your string instead of the length of the string inside (of which you dont know the content at that stage).

int main(){
    char str[10];
    char copy[10];

    printf("length of str: %ld \n", sizeof(str));
    puts("enter characters:");

    fgets(str, sizeof(str), stdin);
    strcpy(copy,str);

    printf("the copy string: ");
    puts(copy);
    printf("after copy: the size - %zu \n",strlen(copy));
}

Upvotes: 1

Related Questions