Kenyskrachor
Kenyskrachor

Reputation: 21

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?

Upvotes: 0

Views: 3967

Answers (2)

chux
chux

Reputation: 153338

OP's code is subject to a hacker exploit and may cause undefined behavior.

// What happens if the first character read is a null character?
fgets(input, length, stdin);
if (input[strlen(input) - 1] != '\n')

When fgets() reads input, an input null character is not special. It is read and saved like any other character.

If this pathological case, input[0] == 0 and strlen(input) - 1 is SIZE_MAX. input[SIZE_MAX] is certainly an access outside array bounds and so undefined behavior.


A test if fgets() did not read all the line is to set the last buffer character to non-zero and later test if it becomes 0.

assert(input && length > 1);

input[length - 1] = '\n';

// check `fgets()` return value
if (fgets(input, length, stdin) == NULL) {
  return NULL;
}

if (input[length - 1] == '\0' && input[length - 2] != '\n') {
  // more data to read.

Upvotes: 1

cadaniluk
cadaniluk

Reputation: 15229

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.

Upvotes: 3

Related Questions