2013-10-14 162 views
0

我是新手编程,并试图改进我的基本倒数计时器。我不知道为什么我会得到这个错误,其他问题是在不同的情况下,因此不适合我的程序。`const char *'到`char'

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

任何帮助,将不胜感激。

+2

而'progend [5]'对于字符串''start''来说太短 - 无法终止nul字符 –

+0

“出现此错误” - 请考虑在下次添加* full * eror消息 – codeling

回答

1

你试图分配char*char,我假设你想要比较。

使用C++

std::string progend; 

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

} 
+0

谢谢,该程序现在工作 –

1

您正在

if (progend[5] = "end") 

progend[5]分配const char *char变量是保持一个char值的字符数组的一个元素。 "end"不能分配给它。可以使用std::string。然后比较像

std::string progend; 
... 
if(progend == "end") 
{ 
    //your code 
+3

它的任务,而不是比较! –

+1

我没有看到任何比较 – LihO

+0

那么我该如何改变? –

5
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== 
+0

@BenjaminLindley:公平点。编辑:) – LihO

1

时,您提出了一些不同的错误,因此,使用strstr

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

} 

同样所有其他地方

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

cin >> progend[5]; 

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

progend[5] = "start" 

这里有两个错误。为了比较平等,你使用==而不是=。你实际做的是尝试分配一个值。更重要的是,"start"是一个C型字符串,或者更好的指向字符串的第一个字符的指针。

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

#include <string> 
using namespace std; 

// etc. 

String progend; 

而且,与progend取代progend[5]所有情况下,你是不是指的特定位置。平等检查也必须是==

我希望这有助于! :D