c++ - `const char*' 到 `char'

标签 c++ string pointers comparison countdown

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

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

相关文章:

c++ - 简单代码需要帮助——没有构造函数的实例匹配参数列表

c++ - 为什么 n*n 在循环的第一个瞬间结果为 4?对我来说应该是 1*1。相反,它是 2*2

c++ - 可以使用 memcpy() 复制包含指针的结构吗?

c++ - 如何在 Qt Creator 的控制台应用程序中将日志打印到文件中?

Swift 跳过 "else if"

c - 短字符串的哈希函数

Python:分割和分析字符串的最有效方法

c - 堆栈指针应该指向顶部的值,还是指向下一个值的位置?

c# - 我应该在 MMORPG 模拟器中使用指针吗?

c++ - 在递归函数上使用 unordered_map unordered_set 的段错误