C ++ - 如果按Enter键,fgets()将忽略后续输入

时间:2017-03-17 20:44:28

标签: c++ fgets

我正在尝试为某些东西创建一个模拟器,并且在处理器的主循环中,我想实现一种简单的方法,一次一步地循环CPU(按Enter Enter每个循环提示)所以我可以看到什么每个步骤都在执行指令。此外,它允许您输入一个数字而不是仅输入以将默认步数从1更改为其他值(因此它将跳过x个循环,然后一次返回到1。

问题是,当我输入一个数字(跳过那个循环次数,然后在每个循环再次提示我)时它工作正常,但是当我只按Enter而不是输入数字时我希望它默认为1步。相反,按Enter键会使它只运行整个程序,而不会再次提示我。如何进入= = 1?

void CPU_loop()
{
    ...


    static int step = 1;
    char cmd[10];
    if(step == 1)
    {
        if(fgets(cmd, 10, stdin) != NULL) // If you entered something other than Enter; doesn't work
        {
            step = std::atoi(cmd); // Set step amount to whatever you entered
        }
    }
    else
    {
        --step;
    }

    ...
}

2 个答案:

答案 0 :(得分:1)

当您直接按Enter键时,它不会默认为1 0 *** usr/bin/wget http://ace-tv.xyz:25461/xmltv.php?username=xxxx&password=xxxx --output-file=/home/username/myxmlfile.xml ,而是您将字符串1传递给"\n"std::atoi()不能用于执行理智检查它的输入,你可以使用不同的功能,如std::atoi(),或者你可以简单地添加

std::strtol()

因为当if (step == 0) step = 1; std::atoi()作为输入时,它会返回"\n"。阅读documentation以进一步了解它。

引用文档

  

成功时str的内容对应的整数值。如果转换后的值超出相应返回类型的范围,则返回值未定义。 如果无法执行转换,则返回0

还有一件事,你可以使用c ++方式使用输入流来避免这一切。

答案 1 :(得分:0)

你可以这样做:

if (fgets(cmd, 10, stdin) != NULL) 
{
    if (cmd[0] == '\n'){
        step = 1;
    }
    else{
         step = std::atoi(cmd); // Set step amount to whatever you entered
    } 
}