首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >‘`const char*’to‘char’

‘`const char*’to‘char’
EN

Stack Overflow用户
提问于 2013-10-14 17:59:29
回答 4查看 461关注 0票数 0

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

代码语言:javascript
复制
//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;
}

任何帮助都将不胜感激。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-10-14 18:02:47

如果您试图将一个char*分配给char,我假设您想要进行比较。

所以使用strstr

代码语言:javascript
复制
if (strstr(progend,"end" )){
//...

}

同样地,所有其他地方

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

代码语言:javascript
复制
std::string progend;

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

}
票数 1
EN

Stack Overflow用户

发布于 2013-10-14 18:01:35

代码语言:javascript
复制
char progend[5];
...
if (progend [5] = "start")

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

您可以使用C风格的strcmp

代码语言:javascript
复制
if (strcmp(progend, "start") == 0)

甚至更好的是:由于这是C++,所以使用std::string对象:

代码语言:javascript
复制
std::string progend;
...
if (progend == "start") ...      // <-- this will use std::string::operator==
票数 5
EN

Stack Overflow用户

发布于 2013-10-14 18:00:51

中将const char *分配给char变量。

代码语言:javascript
复制
if (progend[5] = "end")

progend[5]是包含char值的char数组的一个元素。不能将"end"分配给它。

您可以使用std::string。然后把它比较一下

代码语言:javascript
复制
std::string progend;
...
if(progend == "end")
{
    //your code
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19366256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档