我刚开始使用c / c ++而且我经常会遇到这个错误。有时我可以在控制台中键入c,程序将继续正常。但有时它不会,就像这段代码的情况一样。
我正在尝试创建一个简单的计时器/秒表,显示程序开始时经过的秒数。我试图根据变量是1还是0来控制它的开启或关闭状态。
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
int onoff = 1;
if (onoff == 1)
{
int timex = 0;
while (onoff < 1)
{
timex++;
printf("time: %d", timex);
sleep(1000);
}
}
else if (onoff == 0)
{
char timex[] = "off";
printf("the timer is %s", timex);
}
return 0;
}
也许我只需要弄清楚如何调试?如果是这种情况,我是否可以在任何地方学习如何有效地进行调试?
答案 0 :(得分:0)
使用true
/ false
的布尔变量,开/关或任何两个状态变量,这使您的程序更易于阅读。此外,重命名您的变量。
int main()
{
bool timer_on = true;
if (timer_on)
{
int timex = 0;
while (timer_on)
{
++timex;
cout << "time: " << timex << "\n"; // Since you supplied the C++ tag.
sleep(10000); // This is a platform or RTOS specific function.
}
}
else if (timer_off)
{
cout << "The timer is " << timex << "\n";
}
return 0;
}
一个问题是您在timex
语句的然后部分内定义了if
,但else
部分内的代码无法访问该部分。
您错过了else
阶梯的最终if-else if
条款。也许你想要这样的东西:
else
{
if (!timer_on)
{
}
}
或者内部if
可能不是必需的,因为如果timer_on是else
,代码将在false
语句中执行。