Question: 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]`.

Answer: 
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);

```
As I read from another answer, you could perform this through a scanf function like this:

```
scanf("%3s", string);

```

Where 3 is the maximum number of characters able to be read. Remember that if you want to read n characters, your array has to be n+1 long because of the null terminator '\0'

Hope this helps,