C++中关于getline()输入char数组问题~

//创建一个汽车结构,并且输出输入的汽车名和制造年代
#include<iostream>
#include<string>
using namespace std;

struct car
{char name[20];
int year;
};

int main()
{int i;
cout<<"How many cars do you wish to catalog? ";
cin>>i;
car * pc=new car[i];
cout<<"Car #1: "<<endl;
cout<<"Please enter the make: ";
cin.getline(pc->name,20); //1处
cout<<"please enter the year made: ";
cin>>pc->year;//无法输入,直接跳到末尾。
cout<<"Car #2: "<<endl;
cout<<"please enter the make: ";
cin.getline((pc+1)->name,20);
cout<<"please enter the year made: ";
cin>>(pc+1)->year;
cout<<"Here is your collection; "<<endl;
cout<<pc->year<<" "<<pc->name<<endl;
cout<<(pc+1)->year<<" "<<(pc+1)->name<<endl;
delete [] pc;
return 0;
}

为什么我在1处输入了一行名字之后就什么都不能输入了,程序直接运行到结束?请各位前辈帮我改正正确~谢谢
加入cin.get()也无用,请大家帮我测试下~

第1个回答  2008-07-20
无法输入,就在前面加条语句试试,作用是清空缓冲区.

int ch;
while( (ch = getchar()) != EOF && ch != '\n');
第2个回答  2008-07-20
因为getline()不读入换行符,它被cin读入,所以无法给pc->year赋值。本回答被提问者采纳
相似回答