这里是菜鸟问题,但我正在自学 C 并尝试以安全、正确的方式找出用户输入(供引用,这是 GNU C 编程教程 10.6 (58-59) 中的莫尔斯电码数组练习,以及15.5.5 (107)).
我想要的程序流程是:
- 提示用户输入一个数字
- 获取用户输入
- 验证用户输入
- 如果有效则打印正确的数组项
问题在于,如果用户简单地输入硬回车,数组读取函数会从 my_array[0] 读取并打印。我不知道如何导致返回验证失败。
主要是:
if (get_line (digit_input, sizeof (digit_input), stdin) != NULL ) {
if (validate (digit_input) == 0) {
digit = atoi (digit_input);
printf("\nThe Morse code for %d is: ", digit);
morse(digit);
}
get_line 和验证函数:
char *get_line(char *s, size_t n, FILE *f) {
unsigned int last;
char *p = fgets (s, n, f);
if (p != NULL) {
last = (strlen(s) - 1);
if (s[last] == '\n') s[last] = '\0';
}
return p;
}
int validate(char *a) {
unsigned x;
for (x = 0; x < strlen(a); x++)
if ( !isdigit(a[x]) || (a[1] != '\0' )) return -1;
return 0;
}
如何使空白输入无效? (即,如果字符串读取\n\0?)为什么将无字符(即\n)输入变为 0 并传递给数组读取函数?
谢谢大家的帮助!
最佳答案
如果 strlen()
为 0,您的 validate
函数将返回 0,这不是您想要的。
关于c - 单字符用户输入和 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8703770/