Search code examples
cstringstring-length

How can I read from keyboard a string of only 4 alphanumeric characters, not one less, not one more


I need to understand how to read from keyboard a string of a precise number of characters.

This function is called from the main.

void get_string(char *prompt,
            char *input,
            int length)
{
    printf("%s", prompt);

    if (!fgets(input, length, stdin))
    {
        printf("\nErrore: Inserisci correttamente la stringa.\n");
        get_string(prompt, input, length);
    }
    return;
}

The string, after being acquired, will be copied into input [length].


Solution

  • use scanf("%4s"). The 4 before the s stops saving the input after 4th char.

    char buf[4];
    scanf("%4s", buf);
    printf("%s\n", buf);
    
    input:  123abc
    output: 123a
    

    This solution is wrong ,as it would read not only alphanumeric.

    My 2nd attempt was changing the scanf to this scanf("%4[a-zA-Z0-9]s", buf); but that would stop upon a non-alphanumeric, so still no good.

    A correct way would be this (loop, scan 1 char, check if alphanumeric):

    char buf[32] = "";
    for(unsigned idx = 0; idx < 4; )
    {
        int c = getchar();
        if(isalnum(c))
        {
            buf[idx] = c;
            idx++;
        }
    
    }
    printf("%s\n", buf);