0

I am trying to find the length of the input string using fgets and strlen but I have came across some issues where the null terminating character is unable to be detected.

By empty input string I mean just pressing enter without entering anything.

I have used strlen on the input of empty string and outputs 1 where is should be 0.

int func(char *input) {
    if (input[0] == '\0')
        printf("null detected\n");
    else
        printf("null not detected\n");

    printf("len: %lu", strlen(input));
}


int main() {
    char input[256];
    fgets(input, sizeof(input), stdin);
    func(input);
    return 0;
}

output: null not detected

correct output: null detected

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Mr Habibbi
  • 31
  • 4
  • 2
    Read the [documentation](https://en.cppreference.com/w/c/io/fgets) of `fgets`: the `\n` (newline character) is stored by fgets, so if you just press the Enter key, the content of the buffer will be `"\n"`, that is a single newline character followed by a null character. – Jabberwocky Mar 13 '23 at 09:30

1 Answers1

0

The function fgets can append the entered string with the new line character '\n' that corresponds to the pressed key Enter if the destination character array has enough space to accommodate it.

From the C Standard (7.21.7.2 The fgets function)

2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

So in your case when you just pressed the Enter key the array input looks like

{ '\n', '\0' }

So input[0] is not equal to '\0'. input[0] will be equal to '\n'.

If you declare the array like

char input[1];

and will press at once the Enter key when entering a string then indeed input[0] will be equal to '\0' because the destination array does not have a space to store the new line character '\n'.

If you want to remove the new line character from an entered string you can write for example

input[ strcspn( input, "\n" ) ] = '\0';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335