Kain
Kain

Reputation: 359

strlen() returning a wrong value

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

int main()
{
  char string[100];

  printf("Input string: ");
  fgets(string, sizeof(string), stdin);
  printf("%ld\n", strlen(string));

  return 0;
}

To my knowledge strlen() returns the length of a string excluding the \0 but when i input "hello" it returns a value of 6

Upvotes: 1

Views: 1297

Answers (2)

Jardel Lucca
Jardel Lucca

Reputation: 1203

Print the string as hexadecimal and you will see that the new line character \n or 0x0A is included:

size_t i = 0;
for (; string[i] != 0; i++) {

    printf("string[%zu] = %02X\n", i, (unsigned char)string[i]);
}

Output:

Input string: hello
6
string[0] = 68
string[1] = 65
string[2] = 6C
string[3] = 6C
string[4] = 6F
string[5] = 0A

EDIT: Fixed code for not handling correctly signed char to int promotion and removed unnecessary strlen from loop as very well recommended by @phuclv.

Upvotes: 1

Programmer Hobbyist
Programmer Hobbyist

Reputation: 309

The fgets() function adds a '\n' character to the end of the inputted string. That is why strlen() is returning +1 value. Therefore, strlen() is not returning the wrong length, rather your inputted string has an extra character.

Or to be more precise, there is always a newline character at the end of an input string, but fgets() doesn't remove it unlike other functions such as scanf() or gets(don't use it!)

If you print the ASCII character of the last element of the string, you'll see that it is printing 10. And 10 is the ASCII value of the newline character.

Upvotes: 0

Related Questions