【问题标题】:How to allow user to input alphabets with space for name( e.g. John Mike) but disallow user to input alphabets with digits value?如何允许用户输入带有空格的字母(例如 John Mike),但不允许用户输入带有数字值的字母?
【发布时间】:2017-11-03 13:05:28
【问题描述】:

我想创建一个简单的 C 程序,让用户输入他们的名字并打印出他们的名字(例如 John Mike)。但我也希望程序禁止用户在名称中输入带有数字值的名称(例如 John34 Mike)。

我知道如何使用scanf("%[^\n]",&name);,但用户可以意外在输入名称中输入数字。 我想禁止用户输入带有数字值的字母。 有没有办法解决这个问题?

【问题讨论】:

  • 在标准 C 中没有办法过滤输入的键对键,所以如果你想这样做,你需要使用一些特定于平台的代码(可能包装在一些库中)。您可以在输入完成后进行检查,但不能停止输入数字。
  • 感谢您的建议

标签: c programming-languages


【解决方案1】:

如何允许用户输入带有空格的字母(例如 John Mike),但不允许用户输入带有数字值的字母?

将输入的整个读入一个字符串,然后处理该字符串。


评估字符串的合法字符和模式。

重要的是要在有效的事情上慷慨并考虑各种文化问题。名称有效性测试是一个敏感问题。很容易得到negative feed 尝试讨论它。也可以考虑not constructive

使用isalpha() 进行第一级检查,然后检查其他有效字符以确保至少有一个字母。

isalpha()locale 敏感,并提供一些 级别的国际化。

#include <ctype.h>
#include <stdbool.h>
bool name_test1(const char *s) {
  const char *between_char = "-'";  // Allow O'Doul, Flo-Jo.  Adjust as needed
  bool valid = false;
  while (*s) {
    if (isalpha((unsigned char ) *s)) {
      valid = true;
    } else if (*s == ' ' && valid) { // or  isspace((unsigned char) *s) for any white-space
      valid = false; // valid char must follow
    } else if (strchr(between_char, *s) != NULL && valid) {
      valid = false; // valid char must follow
    } else {
      return false;
    }
    s++;
  }
  return valid;
}

*s == ' ' &amp;&amp; valid 中的 &amp;&amp; valid 确保前导空格无效。

例子:

void ntest(const char *s) {
  printf("%d <%s>\n", name_test1(s), s);
}

int main(void) {
  ntest("John Mike");
  ntest("John34 Mike");
  ntest("John Mike ");
  ntest(" John Mike");
  ntest("Flo-Jo");
  ntest("O'Doul");

  char name[100];
  while (fgets(name, sizeof name, stdin)) {
    name[strcspn(name, "\n")] = '\0';  // lop off potential trailing \n
    if (name_test1(name)) puts("Acceptable name");
    else puts("Unacceptable name");
  }
}

1 <John Mike>
0 <John34 Mike>
0 <John Mike >
0 < John Mike>
1 <Flo-Jo>
1 <O'Doul>
...

最好使用scanf("%[^\n]",&amp;name); 它有问题:它读取几乎一行,'\n' 未被读取。只有"\n" 的一行是个问题。它没有防止缓冲区过度运行的保护。

【讨论】:

    【解决方案2】:

    使用getline 函数获取输入。然后通过isdigit函数检查字符串是否允许输入字符串。

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int main(int argc, char *argv[])
           {
               FILE *stream;
               char *line = NULL;
               size_t len = 80;
               ssize_t nread;
    
    
    
               nread = getline(&line, &len, stdin);
               printf("Retrieved line %s", line);
           for(int i=0;line[i]!='\0';i++)
            if(isdigit(line[i])){
                printf("Disallow\n");
                    return 0;}
           printf("Allow\n");
           return 0;    
    
           }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多