Home > Enterprise >  Limit how many chars accepted in input - Wordle clone
Limit how many chars accepted in input - Wordle clone

Time:07-15

i just finished a project for school and im now polishing some simple things i ignored until the program worked fine. Im almost done but I realized I dont know how to limit the amount of chars i can accept on input. For ex: i have this fragment of code:

printf("\nIngrese su intento:  ");
scanf("%s", &intento);

The project is a wordle clone so it ALWAYS should be 5 chars, not 1more or 1less, how do i limit it to only accept 5 and in case user inputs lets say 8, tell the user "no, do it again". Googling i found this:

Anything or nothing. Welcome to undefined behavior. Writing beyond the end of an array / buffer causes undefined behavior. What happens when undefined behavior happens is not predictable. Maybe it works correctly. Maybe your program crashes. Maybe you corrupt data and cause a security problem. Maybe your hard-drive gets formatted.

Ok. Now i know that even though it sometimes work, i shouldnt do it cause in some random case, it might not... how do i fix this? how do i limit the input with chars? i've already done this with int because its easier but i dont know how to approach it with text.

printf("Bienvenido a Wordle, cuantas partidas deseas jugar en tu sesion de juego?  ");
scanf("%d", &cantPartidas);

while (cantPartidas > 8 || cantPartidas < 1) {

    printf("\nLo sentimos, el numero de partidas por sesion tiene que estar entre 1 y 8 :( \nIngresa un numero dentro del rango:  ");
    scanf("%d", &cantPartidas);
}

printf("\nGenial! Empecemos.");

CodePudding user response:

You can limit the upper bound by using %5s like so

scanf("%5s", cantPartidas);

This makes sure you don't write into memory that is not allocated. Generally, the length of any string can be checked with the strlen() function that is in the string.h library so you can use that to make sure your string has exactly 5 chars in it.

CodePudding user response:

In order to read an entire line of input, I recommend that you use the function fgets. I do not recommend that you use the function scanf, because it is not designed for line-based user input.

The function scanf will do strange unintuitive things, such as not always read an entire line of input at once. The function fgets, on the other hand, will always read exactly one line of user input, assuming that the supplied memory buffer is large enough to store the entire line.

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

int main( void )
{
    char line[200];

    //repeat forever until input is valid
    for (;;) //infinite loop, equivalent to while(1)
    {
        char *p;

        //prompt user for input
        printf( "Enter your attempt: " );

        //attempt to read one line of input
        if ( fgets( line, sizeof line, stdin ) == NULL )
        {
            fprintf( stderr, "Input error!\n" );
            exit( EXIT_FAILURE );
        }

        //find newline character, if it exists
        p = strchr( line, '\n' );

        //determine whether newline character was missing
        if ( p == NULL )
        {
            int c;

            printf( "Line too long for input buffer!\n" );

            //discard remainder of line
            do
            {
                c = getchar();

            } while ( c != EOF && c != '\n' );

            continue;
        }

        //remove newline character
        *p = '\0';

        //make sure that exactly 5 characters were entered
        if ( p - line != 5 )
        {
            printf( "Please enter exactly 5 characters!\n" );
            continue;
        }

        //input is valid, so break out of infinite loop
        break;
    }

    printf( "Input is valid.\n" );
}

This program has the following behavior:

Enter your attempt: mike
Please enter exactly 5 characters!
Enter your attempt: jeremy
Please enter exactly 5 characters!
Enter your attempt: james
Input is valid.
  •  Tags:  
  • c
  • Related