在 C 中循环后跳过 scanf [英] scanf skipped after loop in C

查看:43
本文介绍了在 C 中循环后跳过 scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#define len 100

char sourceString[len];
char command;

int main(void)
{
    while (1)
    {   
        printf("\nEnter source: ");
        fgets(sourceString, len, stdin); // this gets skipped on second loop.

        printf("\nEnter command: ");
        scanf(" %c", command) 

        switch (command)
        {
        case 'A':
            printf("%s", sourceString);
            break;

        case 'B':
            printf("filler");
            break;

        default:
            break;
        }
    }

    return 0;
}

无论是使用 fgets 还是 scanf,字符串总是在第二个循环中被跳过.我尝试在第二个 scanf "%c" 中添加一个空格,但它仍然跳过字符串输入,是的,我试图读取一行然后读取一个字符.

Whether im using fgets or scanf the string always gets skipped on the second loop. I tried adding a space to the second scanf " %c" but it still skips the string input, yes im trying to read a line and then a character.

推荐答案

在scanf调用后插入以下调用

After the call of scanf insert the following calls

    scanf( "%*[^\n]" );
    scanf( "%*c" );

从输入缓冲区中删除换行符\n".

to remove the new line character '\n' from the input buffer.

这篇关于在 C 中循环后跳过 scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆