在 C 中使用 getchar()

Working with getchar() in C

我正在编写一个程序来验证用户输入的用户名。出于本项目的目的,我们允许使用字母(大写或小写)、数字或下划线,但不允许使用空格或其他标点符号。总长度也必须在 5 到 10 个字符之间。 我相信我的问题出在 getchar() 上,因为我知道它一次只能容纳一个字符,但我不完全确定修复它的最佳方法。目前,当我 运行 我的代码时,它只会返回无效。我是否需要更改循环或对其进行调整?还是我的 if 语句有问题?

#include <stdio.h>
#include <ctype.h>

int main(void)
{


    int ch;
    int len = 0;


    printf("Enter the username: "); //prompt user to enter a username
    ch = getchar();


    while (ch != '\n') //while loop checking for length of username
    {
        len++;
        ch = getchar();
    }

    if(isspace(ch) || ispunct(ch) || len > 10 || len < 5){

            printf("invalid input.");
    }

    else{
    printf("valid input.");
    }

    return 0;

}

问题出在这个函数上:isspace(ch)。如果字符是白色,它 return 是一个非零值(真)-space。标准白-space是

' '   (0x20)    space (SPC)
'\t'    (0x09)  horizontal tab (TAB)
'\n'    (0x0a)  newline (LF)
'\v'    (0x0b)  vertical tab (VT)
'\f'    (0x0c)  feed (FF)
'\r'    (0x0d)  carriage return (CR)

由于您执行的最后一个操作是按回车键,因此最后一个字符将是换行符或回车符 return,具体取决于 OS('\r\n', '\n'或 '\r').

我相信您打算检查名称中字符之间是否有 space。你这样做的方式,你只检查最后一个。 您可以将所有字符添加到缓冲区并稍后检查,或者更改初始 while 条件以检查无效字符。

编辑 由于您似乎仍然对评论有问题,我决定在这里添加一个可能的解决方案:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    int ch;
    int len = 0;

    printf("Enter the username: "); //prompt user to enter a username
    ch = getchar();


    while (!isspace(ch) && !ispunct(ch)) //while loop checking for length of username. While it's not(note the exclamation mark) a whitespace, or punctuation, it keeps going(newline is considered a whitespace, so it's covered by the loop).
    {
        len++;
        ch = getchar();
    }

    if (ch == '\n' && len <= 10 && len >= 5) {//if it found the newline char(considering the newline is \n), it means it went till the end without finding other whitespace or punctuation. If the lenght is also correct,then the username is valid
      printf("valid input.");
    }
    else {//if the loop stopped because it found a space or puncuation, or if the length is not correct, then the input is invalid
      printf("invalid input.");
    }

    return 0;
}