C++ - 如果按下 Enter,fgets() 将忽略后续输入
C++ - fgets() ignores subsequent inputs if Enter is pressed
我正在尝试为某些东西创建一个模拟器,在处理器的主循环中我想实现一种简单的方法来一次步进 CPU 一个循环(通过按 Enter each loop 提示) 这样我就可以看到每一步正在执行什么指令。此外,它允许您输入一个数字,而不仅仅是 Enter 以将默认步长量从 1 更改为其他值(因此它将跳过 x 个循环,然后一次 return 到 1。
问题是当我输入一个数字时它工作正常(跳过那个循环数然后每个循环再次提示我),但是当我只是按 Enter 而不是输入数字时我希望它默认为 1步。相反,按 Enter 键会导致它在整个程序中仅 运行,而不会再次提示我。如何让 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;
}
...
}
当你直接回车的时候,它不会默认为1
,而是将字符串"\n"
传递给std::atoi()
,std::atoi()
不能用于对其输入执行健全性检查,你可以使用不同的函数,比如 std::strtol()
或者,你可以简单地添加
if (step == 0)
step = 1;
因为当 std::atoi()
将 "\n"
作为输入时,它 returns 0
。阅读 documentation 以进一步了解它。
引用文档
Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, the return value is undefined. If no conversion can be performed, 0 is returned.
还有一件事,您可以使用流作为输入的 C++ 方式来避免这一切。
你可以这样做:
if (fgets(cmd, 10, stdin) != NULL)
{
if (cmd[0] == '\n'){
step = 1;
}
else{
step = std::atoi(cmd); // Set step amount to whatever you entered
}
}
我正在尝试为某些东西创建一个模拟器,在处理器的主循环中我想实现一种简单的方法来一次步进 CPU 一个循环(通过按 Enter each loop 提示) 这样我就可以看到每一步正在执行什么指令。此外,它允许您输入一个数字,而不仅仅是 Enter 以将默认步长量从 1 更改为其他值(因此它将跳过 x 个循环,然后一次 return 到 1。
问题是当我输入一个数字时它工作正常(跳过那个循环数然后每个循环再次提示我),但是当我只是按 Enter 而不是输入数字时我希望它默认为 1步。相反,按 Enter 键会导致它在整个程序中仅 运行,而不会再次提示我。如何让 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;
}
...
}
当你直接回车的时候,它不会默认为1
,而是将字符串"\n"
传递给std::atoi()
,std::atoi()
不能用于对其输入执行健全性检查,你可以使用不同的函数,比如 std::strtol()
或者,你可以简单地添加
if (step == 0)
step = 1;
因为当 std::atoi()
将 "\n"
作为输入时,它 returns 0
。阅读 documentation 以进一步了解它。
引用文档
Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, the return value is undefined. If no conversion can be performed, 0 is returned.
还有一件事,您可以使用流作为输入的 C++ 方式来避免这一切。
你可以这样做:
if (fgets(cmd, 10, stdin) != NULL)
{
if (cmd[0] == '\n'){
step = 1;
}
else{
step = std::atoi(cmd); // Set step amount to whatever you entered
}
}