C++primer plus的一道题,为什么运行时老跳过cin.getline?
设计一个名为car的结构,用它存储下述有关汽车的信息:生产商(存储在字符数组中的字符串)、生产年份(整数)。编写一个程序,向用户询问有多少辆汽车。随后,程序使用new来创建一个由相应数量的car结构组成的动态数组。接下来,程序提示用户输入每辆车的生产商(可能有多个单词组成)和年份的信息。请注意,这需要特别小心,因为它将交替读取数值和安符串。最后,程序将显示每个结构的内容。该程序运行情况如下(2,Hudson Hornet,1952,Kaiser,1951,是要用户输入的,最后2行是程序回显):
How many cars do you wish to catalog? 2
Car #1:
Please enter the maker: Hudson Hornet
Please enter the year made: 1952
Car #2:
Please enter the maker: Kaiser
Please enter the year made: 1951
Here is your collection:
1952 Hudson Hornet
1951 Kaiser
代码如下:
#include <iostream>
using namespace std;
struct car
{
char producer[20];
int year;
};
int main()
{
int n,i;
cout<<"How many cars do you wish to catalog?";
cin>>n;
car* p=new car [n];
for(i=0;i<n;i++)
{
cout<<"Car #"<<i+1<<endl<<"Please enter the make:";
cin.getline(p[i].producer,20);
cout<<endl<<"Please enter the year made:";
cin>>(p+i)->year;
};
cout<<endl<<"Here is your collection:";
for(i=0;i<n;i++)
cout<<endl<<p[i].year<<" "<<(p+i)->producer;
delete [] p;
return 0;
}
用的VC++6.0,每次运行的时候cin.getline(p[i].producer,20);都没有起作用,直接跳过。改成cin>>的话就不会这样。请教各位大神,问题究竟出在哪儿了??