Search code examples
cstringstring-length

How to check the length of an input String in C


I have this function that check if the string is this:

void get_string(char *prompt, char *input, int length)
{
    printf("%s", prompt);                                   
    fgets(input, length, stdin);
    if (input[strlen(input) - 1] != '\n')
    {
        int dropped = 0;
        while (fgetc(stdin) != '\n')
        {
            dropped++;
        }
        if (dropped > 0)
        {
            printf("Errore: Inserisci correttamente la stringa.\n");
            get_string(prompt, input, length);
        }
    }else{
        input[strlen(input) - 1] = '\0';
    }
    return;
}

With this function I can repeat the input only if the string is longer than length.

How can I do if I must check also if the string is shorter?


Solution

  • If the string is shorter, fgets takes care of that. The buffer won't be full, the newline will be placed at the end of the string.

    Simply check if strlen(input) < length after fgets. If that condition evaluates as true, you read less than the maximum of bytes made possible by the size of the buffer.