关于cin.get()的疑问。

来源:百度知道 编辑:UC知道 时间:2024/07/03 02:58:39
#include<iostream>
#include<string>

using namespace std;

struct car
{
string name;
int year;
};

int main()
{
int x,i;
cout<<"how many cars do you have?";
cin>>x;
cin.get();
car* ps=new car[x];
for(i=0;i<x;++i)
{
cout<<"car #"<<i+1<<":\n";
cout<<"please enter the make:";
getline(cin,ps[i].name);
cout<<"please enter the year made:";
cin>>ps[i].year;
}
cout<<"here is your collection:\n";
for(i=0;i<x;++i)
cout<<ps[i].year<<"\t"<<ps[i].name<<endl;
delete [] ps;
return 0;
}

1.为什么程序在接受“please enter the make:”输入时要读取两次回车?
2.如果去掉cin>>x后面那行cin.get(),为什么程序只接受“please enter the make:”的第一次输入?
3.为什么改用char数组代替string类输入就没有这个问题???
4.还有,cin是不是

不知道你用什么编译器,我用GCC编译没有问题,应该是编译器的问题。
我出现的问题是,当汽车数为一时,程序正常退出;
当为2时,第一次正常,第二次的时候将跳过输入make,直接到输入年份,第3次第4次等等都一样,结果就是只第一次好用。
我分析的原因是getline是string流,不是istream流,getline以回车为输入结尾,一个程序块内的流在第一次使用后,输入回车结尾以后,字符流一直放在缓存里没有被清空,导致下一次getline的时候,因为回车还在直接就结束了。

#include<iostream>
#include<string>

using namespace std;

struct car
{
string name;
int year;
};

int main()
{
int x,i;
cout<<"how many cars do you have?";
cin>>x;
car* ps=new car[x];

for(i=0;i<3;i++)
{
fflush(stdin);//加上这个 缓冲区的问题
cout<<"car #"<<i+1<<":\n";
cout<<"please enter the make:";
getline(cin,ps[i].name);
cout<<"please enter the year made:";
cin>>ps[i].year;

}
cout<<"here is your collection:\n";
for(i