c - 为什么这段代码没有正确重新提示?
问题描述
我对 C 完全陌生。当输入值不是数字时,我想重新提示,当它是数字时,它应该小于 1。当我给出任何类型的字符串时,它都能正常工作。但是当我给出任何数字时,它会转到下一行而不打印“Number:”。然后在下一行,如果输入值小于 1,它会再次打印“Number:”。
int x;
printf("Number: ");
while (scanf("%d", &x) != 1 || x < 1 )
{
printf("Number: ");
scanf("%*s");
}
它给我的结果是这样的
解决方案
fgets
使用读取行,然后使用sscanf
解析输入是明智的。这样就可以拿到线,然后检查是否sscanf
成功!简单的例子:
int target_number; // The number you will have at the end of this.
while (1) { // Loop for rechecking number
char line[16]; // See notes on how to read the whole line.
fgets(line, sizeof(line), stdin);
// We use 1 here because sscanf returns the number of format specifiers that are matched. Since you only need one number, we use 1.
if (sscanf(line, "%d", &target_number) != 1) {
fprintf(stderr, "Invalid Input! Please enter in a valid number.");
continue;
}
}
// Do whatever you will with target_number
笔记
您可以在此处查看如何阅读整行。
这段代码不安全!
它不能防止缓冲区溢出攻击等。请以正确的方式查看此内容。如果这只是为了学习,你不必担心。
推荐阅读
- html - 在本地 HTML 文件中嵌入 Google 趋势图时遇到问题
- python - 如何使用目录在 jupyter notebook 上导入 .py 文件
- reactjs - ReactJS 自定义钩子,根据它的数据再次调用
- php - PHP - 使用 PhpSerial 发送十六进制
- flutter - 我有一条从 A 点到 B 点的线,我想在画布 CustomPainter Flutter 中以相同的角度将线延伸到 C 点到外半径
- reactjs - 如何从类父组件调用功能性子组件方法
- mongodb - 如何在mongodb中查询数组中的每个元素以返回所有元素都满足条件的文档
- doxygen - Doxygen 项目简介可以包含链接吗?
- sql - 使用 CRON 表达式生成日期时间
- scala - Spark Scala FoldLeft 性能缓慢