c - 接收输入时出错

标签 c

我经常看到这样的情况,在一系列要求输入的 printf 语句中,某些 语句不接受输入,即

printf_statement1:

printf_statement2: /*Enter input here*/

即在用户为 statement1 输入输入之前,打印 statement2,允许用户输入输入,然后对 statement3 重复相同的操作&语句4

什么原因导致出现这种情况?

我遇到过这种情况,但现在不再遇到了,在:

 printf("\n\n\t\tName: ");
 scanf("%s", name); //initially used gets
 printf("\n\n\t\tType: ");     
 scanf("%c", &type);
 printf("\n\n\t\tAddress: ");      //initially used gets
 scanf("%s", address);
 printf("\n\n\t\tDate - of - Birth: ");
 scanf("%s", dob); //initially used gets

输出:

Name:
Type: I enter something!
Address:
Date - of - Birth: I enter something!

最佳答案

我知道这个问题已经被标记为已回答,但由于 fflush(stdin) 让我感到畏缩,我想发布一个清除 stdin 的替代方法:

void clear_stdin(void)
{
   int c;
   do {
      c = fgetc(stdin);
   } while (c != '\n' && c != EOF);
}

这将清除所有char,直到出现新行或遇到EOF。 (您可以将 do..while 的主体和条件粘贴到 while 循环的条件中,但我更喜欢这样编写。)

例如,在想要读取单个 char 后调用该函数会很有用,以防止用户输入超过 1 个字符时似乎跳过后续提示。

还可以考虑使用 fgets() 或通过 scanf() 提供宽度说明符以防止溢出。

关于c - 接收输入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8798063/

相关文章:

c - on_exit 和 CTRL+C

c++ - 如何通过读取文件将不同数据类型的数据推送到一个 vector 中?

c - exit(0) 的目的是什么?

c - 程序显示内存泄漏,即使在使用 free() 之后

c++ - 在哪里可以找到 size_t 的定义?

c++ - 如何从文件中读取 unsigned short?

c - 如何使此代码适用于大输入值?

c - 进程线程被 __pthread_enable_asynccancel () 卡住

c - 从线程调用的函数中退出 pthread_exit

c - 如何在 GTK+3 中处理双击事件?