我怎样才能从键盘上读取一个只有 4 个字母数字字符的字符串,不能少,不能多

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

我需要了解如何从键盘读取精确字符数的字符串。

此函数是从 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;
}

获取后的字符串将复制到input [length].

使用scanf("%4s")s 之前的 4 在第 4 个字符后停止保存输入。

char buf[4];
scanf("%4s", buf);
printf("%s\n", buf);

input:  123abc
output: 123a

这个解决方案是错误的,因为它不仅会读取字母数字。

我的第二次尝试是将 scanf 更改为 scanf("%4[a-zA-Z0-9]s", buf);,但这会停止在非字母数字上,所以仍然没有用。

正确的方法是这样(循环,扫描 1 个字符,检查是否为字母数字):

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

}
printf("%s\n", buf);

正如我从另一个答案中读到的那样,您可以通过这样的 scanf 函数执行此操作:

scanf("%3s", string);

其中 3 是能够读取的最大字符数。请记住,如果你想读取 n 个字符,你的数组必须是 n+1 长,因为空终止符 '\0'

希望对您有所帮助,