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;