【发布时间】:2017-09-09 22:54:03
【问题描述】:
我正在编写一个程序来验证用户输入的用户名。出于本项目的目的,我们允许使用字母(大写或小写)、数字或下划线,但不允许使用空格或其他标点符号。它还必须总共有 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;
}
【问题讨论】:
-
你需要检查循环中的字符类型。
-
类似question
标签: c loops debugging while-loop getchar