c - Scanf 函数跳过
问题描述
在类似的问题中,读取字符或字符串的 scanf 会跳过,因为在为前一个 scanf 按下“Enter”键后,它会从输入缓冲区中获取一个新行,但我认为这不是问题所在。如果 input1 是一个整数,这个程序不会跳过第二个 scanf,但是对于其他类型的输入(double、char、string 等)它会跳过它。
#include <stdio.h>
#include <string.h>
int main(){
int input1;
char input2[6];
printf("Enter an integer. ");
scanf("%d", &input1);
printf("You chose %d\n", input1);
printf("Write the word 'hello' ");
scanf(" %s", input2);
if (strcmp(input2,"hello")==0){
printf("You wrote the word hello.\n");
} else {
printf("You did not write the word hello.\n");
}
return 0;
}
为什么会这样?
解决方案
代码中的注释:
int input1 = 0; // Always initialize the var, just in case user enter EOF
// (CTRL+D on unix) (CTRL + Z on Windows)
while (1) // Loop while invalid input
{
printf("Enter an integer. ");
int res = scanf("%d", &input1);
if ((res == 1) || (res == EOF))
{
break; // Correct input or aborted via EOF
}
int c;
// Flush stdin on invalid input
while ((c = getchar()) != '\n' && c != EOF);
}
printf("You chose %d\n", input1);
另外,看看如何使用 scanf 避免缓冲区溢出
推荐阅读
- r - 在 R 中将 10 年以上替换为 10 年
- javascript - 当用作对象键时,为什么 JavaScript 将一个字符串的数组转换为字符串?
- c++ - 在没有放置 new 运算符的情况下在预分配的内存上使用虚拟函数初始化对象 - 这可能吗?如果不是,为什么
- reactjs - 'this.props.tasks.map is not a function' 错误-React 错误
- c++ - c ++将结构数组传递给函数
- react-native - 在 React Native 中保存数据
- python - 长轮询的 Ajax 无法在网页上显示 celery 结果
- java - 如何在 Janino 脚本中表示值列表
- php - 将JSON插入Mysql问题(ajax/php)
- docker - 使用docker将kafka主题数据写入redis