我寫了這個代碼(我剛開始編碼BTW),並有一個錯誤在13:17:不兼容類型的分配 '爲const char [2]到char [1]'
error: incompatible types in assignment of 'const char [2]' to '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;
}
首先,'opinion2 =「y」'是一項任務,而不是比較。其次,我強烈推薦使用std :: string而不是字符指針。 –
'opinion1'和''y''都不是'char'。 – MikeCAT