循环输入数据
Input data in loop
我想按格式"%d:%c"输入数据
我有这个:
#include <stdio.h>
int main() {
int number;
char letter;
int i;
for(i = 0; i < 3; i ++) {
scanf("%c:%d", &letter, &number);
printf("%c:%dn", letter, number);
}
}
我期望这个:
Input: "a:1"
Output: "a:1"
Input: "b:2"
Output: "b:2"
Input: "c:3"
Output: "c:3"
但是我的程序是这样做的:
a:1
a:1
b:2
:1
b:2
--------------------------------
Process exited with return value 0
Press any key to continue . . .
这里有什么问题?
这是因为
当您使用 scanf
读取输入时,Enter 字符仍保留在缓冲区中,因此您下次调用 scanf
时会将其读取为字符。
这很容易通过告诉scanf
跳过空格,通过在格式代码中添加一个空格来解决,例如
scanf(" %c:%d", &letter, &number);
/* ^ */
/* | */
/* Notice leading space */
此链接可能会有所帮助。 在 scanf() 函数中在 %d 之后使用 %c 会导致您遇到这样的困难。
简而言之,您在给出第一个测试用例的数字输入后输入的""将被视为第二个测试用例的字符输入。
为避免这种情况,您可以将scanf
语句编辑为 scanf(" %c:%d",...);
.%c 前面的前导空格可避免将所有这些""输入作为字符。
OP 说"...按格式"%d:%c"输入数据,但代码使用"%c:%d"
,数据输入意味着"char"然后是"数字"。
建议:
1) 确定所需的顺序。
2)在"%c"
前使用空格,如" %c"
,以使用前导空格,如前一行的Enter(或'n'
)。
相关文章:
- c ++数据输入并读回列表中的结构结构中的数组
- 为什么我不能从结构将数据输入到字符数组中?
- C 如何忽略错误数据输入
- 如何在 C++ 中将结构类型向量数据输入到结构向量成员(嵌套结构向量)中
- 使用 for 循环多次将数据输入到 txt 文件
- C 从文本文件中将数据输入INT矢量
- 将数据输入两个字符串
- 带有 QSqlTableModel 的 QTableView 的数据输入
- C++用户将数据输入 2D 数组的最简单方法是什么?
- C++LinkedList数据输入
- 将数据输入到 2-D 数组中,这是如何工作的
- C++ 将数据输入私有向量时遇到问题(使用无效)
- 使数据输入字段记住其值,从一次运行到下一次运行
- C++ 将数据输入到用户定义类型的向量
- 我不知道如何正确地将数据输入到地图中
- 如何通过输入终止数据输入
- WHILE循环和数据输入
- 不按我的要求显示数据输入表单
- 用键盘将数据输入Qt GUI:按下回车键时会产生意想不到的副作用
- c++为不符合条件的数据输入创建循环