【问题标题】:Working with getchar() in C在 C 中使用 getchar()
【发布时间】: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


【解决方案1】:

问题出在这个函数上:isspace(ch)。如果字符是空格,则返回非零值(true)。标准空格是

' '   (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)

由于您执行的最后一个操作是按 Enter,因此最后一个字符将是换行符或回车符,具体取决于操作系统('\r\n'、'\n' 或 '\r')。

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

编辑 由于您似乎仍然遇到来自 cmets 的问题,因此我决定在此处添加一个可能的解决方案:

#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;
}

【讨论】:

  • 好的。我认为问题可能是我只检查最后一个字符,所以我很高兴听到我至少在正确的轨道上。我需要对我的 while 循环进行哪些更改?我试图添加 'isspace(ch) || ispunct(ch)' 到条件,但后来我意识到它根本不会打扰 while 循环,因为它不满足条件。
  • 好的,所以我完全删除了 isspace(ch) 函数,它似乎正在工作(甚至检测空格..虽然我不确定如何。也许是因为我添加了!= EOF?无论如何我离开了ispunct(ch) in 并且它仍然被接受的标点符号......这是同一个问题,它只检查最后一个字符吗?
  • 好的,我用可能的解决方案编辑了答案,希望对您有所帮助
  • 谢谢!我现在看到问题出在我的 while 语句上,而不是 if else 语句上……有没有可以免除下划线的函数?因为这些应该是有效的。所有其他标点均无效。
  • 我不知道有这样的功能,但您应该能够轻松地更改代码以在 while 循环中使用简单的“或”来接受下划线。很高兴我能帮忙;)
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 2015-09-08
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多