0

我是编程新手,并试图改进我的基本倒数计时器。我不知道为什么会出现此错误,并且其他问题处于不同的情况,因此不适合我的程序。

//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;
}

任何帮助,将不胜感激。

4

4 回答 4

5
char progend[5];
...
if (progend [5] = "start")

尝试将字符串文字分配给数组"start"的第 6 个字符progend(甚至不存在)。请注意,即使此代码尝试分配一个字符,在其结束后写入数组也会导致未定义的行为

您可以使用 C-style strcmp

if (strcmp(progend, "start") == 0)

甚至更好:因为这是 C++,请改用std::string对象:

std::string progend;
...
if (progend == "start") ...      // <-- this will use std::string::operator==
于 2013-10-14T18:01:35.270 回答
1

您正在将 a 分配const char *char变量

if (progend[5] = "end")

progend[5]是保存 char 值的 char 数组的元素。"end"不能分配给它。

您可以使用std::string. 然后像这样比较

std::string progend;
...
if(progend == "end")
{
    //your code
于 2013-10-14T18:00:51.930 回答
1

您正在尝试将 a 分配char*char,我假设您想比较 。

所以使用strstr

if (strstr(progend,"end" )){
//...

}

同样的所有其他地方

但是为什么不使用std::string, 在使用 C++ 时

std::string progend;

if(progend.find("end") != std::string::npos)
{

}
于 2013-10-14T18:02:47.663 回答
1

你犯了许多不同的错误。

cin >> progend[5];

在这里,您要求输入字符,而不是字符串。更重要的是,索引 5 超出了数组的范围(我们从 0 开始计数)。

progend[5] = "start"

这里有两个错误。要比较是否相等,您应该使用==而不是=. 您实际上所做的是尝试分配一个值。更重要的是,"start"是一个 C 类型的字符串,或者更好的是指向字符串的第一个字符的指针。

为什么不简单地使用 C++ STL 中的字符串?

#include <string>
using namespace std;

// etc.

String progend;

另外,用 替换所有实例progend[5]progend您不是指特定位置。平等检查也必须==

我希望这有帮助!!!:D

于 2013-10-14T18:06:54.833 回答