C-用户输入被跳过了吗? [英] C - User input getting skipped?

查看:75
本文介绍了C-用户输入被跳过了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个菜单​​,您可以从中选择一些动作.

I want a menu from which you choose some action.

问题是,当我们选择一个并按下返回"键时,将跳过应该是下一步的用户输入命令.为什么会这样?

Problem is that when we choose one, and press the "return" key, the user input command which should have been the next step, is skipped. Why is that ?

代码是:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int choice;

    do
    {
     printf("Menu\n\n");
     printf("1. Do this\n");
     printf("2. Do that\n");
     printf("3. Leave\n");
     scanf("%d",&choice);

     switch (choice)
     {
        case 1:
            do_this();
            break;
        case 2:
            // do_that();
            break;
     }

    } while (choice != 3);

    return(0);
}

int do_this()
{
    char name[31];

    printf("Please enter a name (within 30 char) : \n");
    gets(name); // I know using gets is bad but I'm just using it

    // fgets(name,31,stdin); // gives the same problem by the way.

    // Problem is : user input gets skiped to the next statement :
    printf("Something else \n");

    return(0);
}

推荐答案

scanf()留下一个换行符,该字符串由后续对gets()的调用所消耗.

scanf() leaves a newline which is consumed by the subsequent call to gets().

scanf()之后立即使用getchar();或使用循环读取和丢弃字符:

Use getchar(); right after scanf() or use a loop to read and discard chars:

int c;
while((c= getchar()) != '\n' && c != EOF); 

我知道您已经评论过gets()不好.但是,即使它是一个玩具程序,您也不应该尝试使用它.它已经从最新的C标准(C11)中完全删除 ,即使您正在为C89编程(由于其缓冲区溢出漏洞),也不应该使用它.使用fgets()几乎相同,除了可能留下尾随换行符.

I know you have commented about gets() being bad. But you shouldn't even attempt to use it even if it's a toy program. It's been removed from the latest C standard (C11) completely and shouldn't be used even if you are programming for C89 (due to its buffer overflow vulnerabilities). Use fgets() which does almost the same except possibly leaves a trailing newline.

如果这是您的完整代码,那么您还需要一个原型或至少一个do_this()的声明.隐式int规则也已从C标准中删除.因此,添加

If this is your complete code, then you would also need a prototype or at least a declaration for do_this(). Implicit int rule has also been removed from C standard. So add,

int do_this();

位于源文件的顶部.

这篇关于C-用户输入被跳过了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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