0

When I directly type a string, like:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char phrase[100] = "lonesomestreet";
    char phrase2[100] = "lonesomestreet";
    printf("String 1 has %d characters, and string 2 has %d characters.\n", strlen(phrase), strlen(phrase2));
    system("pause");
    return 0;

}

It returns 14 characters for both. But if I read them:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char phrase[100];
    char phrase2[100];
    printf("Type a phrase:\n");
    fgets(phrase,100,stdin);
    printf("Type a phrase:\n");
    fgets(phrase2,100,stdin);
    printf("String 1 has %d characters, and string 2 has %d characters.\n", strlen(phrase), strlen(phrase2));
    system("pause");
    return 0;

}

It returns 15 characters for both. Can anyone please explain me why this happens?

An addition. If I count the characters it also gives 15:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char phrase[100];
    char phrase2[100];
    printf("Type a phrase:\n");
    fgets(phrase,100,stdin);
    printf("Type a phrase:\n");
    fgets(phrase2,100,stdin);
    int k=0;
    for (int i=0; phrase[i]!='\0'; i++) {
        k++;
    }
    printf("The phrase has %d characters.\n", k);
    system("pause");
    return 0;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
francescobfc
  • 107
  • 1
  • 11
  • 2
    related : [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) – Sander De Dycker Oct 07 '19 at 13:17

1 Answers1

1

The standard function fgets can append the new line character if there is enough space in the destination character array. You should remove it. For example

#include <string.h>
#include <stdio.h>

//...

fgets(phrase,100,stdin);

phrase[ strcspn( phrase, "\n" ) ] = '\0';

Or your could rewrite your for loop the following way

size_t i = 0;
while ( phrase[i] !='\0' && phrase[i] != '\n' ) ++i;
printf("The phrase has %zu characters.\n", i);

Pay attention to that you shall use the conversion specifier %zu instead of %d when try to output the value returned by the standard C function strlen because the returned value has the type size_t

printf("String 1 has %zu characters, and string 2 has %zu characters.\n", strlen(phrase), strlen(phrase2));
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335