我写了这段代码(我刚刚开始编码btw),并且在13:17发生错误:
错误:将'const char [2]'赋值给'char [1]'的不兼容类型
这个错误也可以在27:25找到。
这不是我如何修复它的问题,而是解释为什么使用if(opinion="y")
不起作用,因为它是一个字符。我已经尝试使用cin.getline()
而没有任何结果(我还没有学到(我确实使用#incude <string>
,即使std
库中包含字符串)
有什么想法吗?
#include <iostream>
#include <string>
using namespace std;
int main(){
int mycarrots=10; //Initiates number of carrots that I have (mycarrots)
int yourcarrots=0; //Inititate the numbe of carrots the user has
int wantcarrots=0; //initiates the number of carrots user wants
int wantcarrots2=0; //initiates how many more carrots user wants apart from the ones that I can give him
char opinion1[1], opinion2[1]; //initiates opinion whether user want carrots. Opionion2 Initiates opinion whether user has enough money to buy more carrots
int ymoney=0; //initiates how much money the user has
cout<<"I have some carrots I want to give away, would you like some? (y/n)"<<endl; //initiates convo, ask user whether he wants carrts
cin>>opinion1; //input of opinion (y/n)
if (opinion1="n"){ //if the opinion is no, execute "Have a good day"
cout<<"Have a good day!"<<endl;
}
else { //otherwise, resume convo
cout<<"How many do you want?"<<endl;
cin>>wantcarrots;
if (wantcarrots>mycarrots){
cout<<"I don't have that many carrots, you'll have to get some from the store."<<endl;
cout<<"They're $1.5 each, so you'll have to pay "<<(wantcarrots-mycarrots)*1.5<<" dollars";
cout<<"do you have enough money for that? (y/n)"<<endl;
cin.getline(opinion2,1);
wantcarrots2=wantcarrots-mycarrots;
if (opinion2="y"){
cout<<"I can give you "<<mycarrots<<" carrots, but you'll have to get the other"<<mycarrots-wantcarrots<<" from the store."<<endl;
cout<<"Now off you go to the store then.";
}
else {
cout<<"how much money do you have?"<<endl;
cin>>ymoney;
if (ymoney>=(wantcarrots2*1.5)){
cout<<"Off you go to the store."<<endl;
}
else if (ymoney<(wantcarrots2*1.5)){
cout<<"You'll have to settle for "<<ymoney/1.5<<" carrots."<<endl;
}
}}
else{
cout<<"fatal errors. i am not prgrammed to do this"<<endl;}
}
else {
cout<<"Here are your "<<wantcarrots<<" carrots"<<endl;
cout<<"now you have "<<yourcarrots<<" carrots"<<endl;}
return 0;
}
答案 0 :(得分:0)
if(opinion="y")
无法正常工作,因为opinion
未声明且if(opinion1="y")
无法正常工作,因为您无法分配到数组。
要检查所阅读的内容是y
,请尝试if(*opinion1 == 'y')
。
积分
opinion1[0]
。更新:正如@SamVarshavchik建议的那样,此代码将导致越界访问。
如果您不更改opinion1
的类型,请使用cin.get(*option1);
代替cin>>opinion1;
答案 1 :(得分:0)
除了在其他答案中指出的此代码的问题之外,我还要指出,如果输入不是空字符串,则会导致内存损坏和未定义的行为。
char opinion1[1]
一个字符数组只能容纳一个空字符串......
cin>>opinion1;
...只要在这里输入一个字符,就会溢出数组缓冲区,破坏堆栈,导致未定义的行为。