我是新编程,并试图改进我的基本倒计时计时器。我不知道为什么会出现这个错误,其他问题也会出现在不同的情况下,因此不适合我的程序。
//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;
}任何帮助都将不胜感激。
发布于 2013-10-14 18:02:47
如果您试图将一个char*分配给char,我假设您想要进行比较。
所以使用strstr
if (strstr(progend,"end" )){
//...
}同样地,所有其他地方
但是为什么不使用std::string,当使用C++
std::string progend;
if(progend.find("end") != std::string::npos)
{
}发布于 2013-10-14 18:01:35
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==发布于 2013-10-14 18:00:51
中将const char *分配给char变量。
if (progend[5] = "end")progend[5]是包含char值的char数组的一个元素。不能将"end"分配给它。
您可以使用std::string。然后把它比较一下
std::string progend;
...
if(progend == "end")
{
//your codehttps://stackoverflow.com/questions/19366256
复制相似问题