运行这段代码,每次输入都为2,结果color 后是空的?如果我改color为int型运行正确了,这是为什么?
#include<cstring>
#include<iostream>
using namespace std;
class ABC
{
private:
string label="0";
int rating=0;
protected:
string Label(){return label;}
int Rating(){return rating;}
public:
ABC(string la="null",int ra=-1):label(la),rating(ra){}
virtual void ViewABC()=0;
};
class lacksDMA:public ABC
{
private:
string color;
public:
lacksDMA(string co="null",string la="null",int ra=-1):ABC(la,ra),color(co){}
virtual void ViewABC()
{
cout<<"\n\nLabel:"<<Label()<<endl;
cout<<"Rating:"<<Rating()<<endl;
cout<<"Color:"<<color<<endl; //不显示color值?
}
};
const int CLIMITES=1;
int main()
{
char c,choose;
ABC *pDMA[CLIMITES];
string latemp,cotemp,sttemp;
int ratemp;
for(int i=0; i<CLIMITES; i++)
{
cout<<"Label is :";
getline(cin,latemp);
cout<<"rating is :";
cin>>ratemp;
cout<<"Color is :";
getline(cin,cotemp);
pDMA[i]=new lacksDMA(cotemp,latemp,ratemp);
while(cin.get()!='\n')
continue;
}
for(int i=0; i<CLIMITES; i++)
{
pDMA[i]->ViewABC();
}
}
问题在于你混用cin 和 getline。
如果你一定要混用的话,可以在cin之后加上