循环输入数据

Input data in loop

本文关键字:数据 输入 循环      更新时间:2023-10-16

我想按格式"%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')。