C++ `常量字符*'到'char'
我是编程新手,并试图改进我的基本倒计时计时器。我不知道为什么会出现这个错误,其他问题处于不同的情况下,因此不适合我的程序C++ `常量字符*'到'char',c++,string,pointers,comparison,countdown,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 pr
//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变量指定一个常量char*
if (progend[5] = "end")
progend[5]是保存char值的char数组的元素。无法为其指定结束
您可以使用std::string。然后像这样比较
std::string progend;
...
if(progend == "end")
{
//your code
尝试将字符串文字开头指定给甚至不存在的progend数组的第6个字符。请注意,即使此代码尝试分配字符,在其结束后写入数组也会导致未定义的行为
您可以使用C型strcmp:
或甚至更好:因为这是C++,所以使用对象代替:
std::string progend;
...
if (progend == "start") ... // <-- this will use std::string::operator==
您试图将char*分配给char,我假设您想要比较
所以使用
其他地方也一样
但是,当使用C时,为什么不使用std::string呢++
std::string progend;
if(progend.find("end") != std::string::npos)
{
}
你犯了许多不同的错误
cin >> progend[5];
在这里,您要求输入字符,而不是字符串。而且,索引5超出了从0开始计数的数组的范围
progend[5] = "start"
这里有两个错误。要进行相等性比较,必须使用==而不是=。您实际做的是尝试分配一个值。更重要的是,start是一个C类型的字符串,或者最好是指向字符串的第一个字符的指针
<>你为什么不直接从C++ STL?< /P>使用字符串?
#include <string>
using namespace std;
// etc.
String progend;
另外,将progend[5]的所有实例替换为progend,因为您没有引用特定的位置。相等性检查也必须为==
我希望这有帮助!!!:它的赋值,而不是比较!我没有看到任何比较,那么我如何改变它?@ BenClayton,使用STD::String和Prime[ 5 ]对于字符串“开始”来说太短了,没有终止NUL的地方来描述这个错误-请考虑下次添加完整的Eror消息。
cin >> progend[5];
progend[5] = "start"
#include <string>
using namespace std;
// etc.
String progend;