我是编程新手,并试图改进我的基本倒数计时器。我不知道为什么会出现此错误,其他问题在不同情况下不适合我的程序。
//countdown timer using while loops, if else, strings and sleep
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main ()
{
char progend[5];
float a; /* a will be floating point */
cout << "Enter start the the number you want to count down from" << ".\n";
while (a>-1) { /* the main program is located here */
cin >> progend[5];
if (progend[5] = "end") /* if the user inputs end the program ends */
{
a = -1;
}
else if (progend [5] = "start")
{
cin >> a;
while (a>0) { /* the actual countdown timer*/
Sleep(100);
a = a - 0.1;
cout << a;
}
cout << "Finished!" << ".\n" << "Enter start then enter another number to count down from or enter end to close the program" << ".\n";
}
else
{
cout << "Enter yes or end";
}
}
return 0;
}
如有任何帮助,我们将不胜感激。
最佳答案
char progend[5];
...
if (progend [5] = "start")
尝试将字符串文字 "start"
分配给 progend
数组(甚至不存在)的第 6 个字符。请注意,即使此代码尝试分配一个字符,在数组结束后写入数组也会导致未定义的行为。
您可以使用 C 风格的 strcmp
:
if (strcmp(progend, "start") == 0)
或者更好:因为这是 C++,所以使用 std::string
对象代替:
std::string progend;
...
if (progend == "start") ... // <-- this will use std::string::operator==
关于c++ - `const char*' 到 `char',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19366256/