c - 在 C 中使用 scanf() 连续读取两个字符

标签 c input character scanf input-buffer

我尝试从用户 t 输入两个字符的次数。这是我的代码:

int main()
{
    int t;
    scanf("%d",&t);
    char a,b;

    for(i=0; i<t; i++)
    {
        printf("enter a: ");
        scanf("%c",&a);

        printf("enter b:");
        scanf("%c",&b);
    }
    return 0;
}

奇怪的是第一次的输出是:

enter a: 
enter b:

即代码不等待a的值。

最佳答案

问题是 scanf("%d", &t) 在输入缓冲区中留下一个换行符,它只被 scanf("%c", &a) 使用code> (因此 a 被分配了一个换行符)。您必须使用 getchar(); 来使用换行符。

另一种方法是在 scanf() 格式说明符中添加一个空格以忽略前导空白字符(这包括换行符)。示例:

for(i=0; i<t; i++)
{
    printf("enter a: ");
    scanf(" %c",&a);

    printf("enter b: ");
    scanf(" %c",&b);
}

如果您更喜欢使用 getchar() 来使用换行符,则必须执行以下操作:

for(i=0; i<t; i++)
{
    getchar();
    printf("enter a: ");
    scanf("%c",&a);

    getchar();
    printf("enter b:");
    scanf("%c",&b);
 }

我个人认为前一种方法更好,因为它忽略了任意数量的空格,而 getchar() 只消耗一个。

关于c - 在 C 中使用 scanf() 连续读取两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24099976/

相关文章:

c - 用c程序处理数组

c - 使用socket通信的程序卡住了

c - 用串口编程C读取多个传感器

android - 如何从 Android 中的 EditText 中读取单个字符?

c - C语言只打印字符串中以指定字母开头的单词

jQuery prop() 方法返回错误的 id

c++ - 使用getline后如何使cin工作?

python - 使用python在字符串中插入字符

string - 最适合填充字符串的字符

c - 为什么要为链接器指定目标架构?