Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check length of user input in C?

I'm kind of new to C, and the input reading is really confusing me. I'm trying to initialize an array of size 4, but sometimes the user will enter valid input of 3. In Java, I could check the length of the input and add conditionals, but I'm not sure how this works in C.

main(void){
        char str[N];
        int i;

        for(i = 0; i < N; i++){
                scanf("%c", &str[i]);
        }

        for(i = 0; i < N; i++){
            printf("%c\n", str[i]);
        }
}

Right now, if I input 4 or more, it works fine. If I input 3, it breaks. I'd like it to handle both 3 or 4 characters.

Actually, the root of the problem is: I'm trying to figure out a way in C to read in a 24-hour-clock time, and add it to a 24-hour-clock duration. Should I be approaching this an entirely different way?

Thanks,

like image 907
Kris Avatar asked Dec 04 '25 19:12

Kris


2 Answers

The short answer is: you can't.

Using scanf() is particularly dangerous because of this if you want to read in a string (%s); if the user enters more input than your buffer can hold, you have a buffer overflow on your hands.

fgets() on the other hand, allows you to specify the max number of bytes you will read, preventing you from overflowing the buffer.

Here's a quick example on how you'd write a function for some input that verified that the input was within a specified length and was a complete line (ending with \n - this routine discards the \n from the input):

void getInput(char *question, char *inputBuffer, int bufferLength)
{
    printf("%s  (Max %d characters)\n", question, bufferLength - 1);
    fgets(inputBuffer, bufferLength, stdin);

    if (inputBuffer[strlen(inputBuffer) -1] != '\n')
    {
        int dropped = 0;
        while (fgetc(stdin) != '\n')
            dropped++;

        if (dropped > 0) // if they input exactly (bufferLength - 1) 
                         // characters, there's only the \n to chop off
        {
            printf("Woah there partner, your input was over the limit by %d characters, try again!\n", dropped );
            getInput(question, inputBuffer, bufferLength);
        }
    }
    else
    {
        inputBuffer[strlen(inputBuffer) -1] = '\0';      
    }
}

int main()
{
    char firstAnswer[10];
    getInput("Go ahead and enter some stuff:", firstAnswer, 10);
    printf("Okay, I got: %s\n",firstAnswer);

}
like image 74
Brian Roach Avatar answered Dec 06 '25 09:12

Brian Roach


scanf() allows the use of maximum width specifiers:

So scanf("%3s", buffer) reads at most 3 characters + 1 NUL terminator.

like image 20
ninjalj Avatar answered Dec 06 '25 08:12

ninjalj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!