回 帖 发 新 帖 刷新版面

主题:关于cin.get()

#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;
[color=008080]cin.get();[/color]
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;
}



为什么去掉绿色那行cin.get(),程序只接受第一行“please enter the make”输入?
而改用char数组代替string类输入就没有这个问题???

谢谢

回复列表 (共1个回复)

沙发

问题在于这里不应该用getline函数,应该将getline(cin,ps[i].name);换成cin>>ps[i].name;,就不会出现这样的问题了,自然也不需要加cin.get();了。

反之,如果你保留了getline的使用,那么前面在cin>>x;输入时,回车符被getline函数直接接收作为它的输入了,所以你根本没有输入机会。因此要加cin.get();来吸收前面的回车,好使你在getline函数时能正常输入。同理,在for循环中的cin>>ps[i].year;之后也要加上cin.get();否则后面的循环输入也无法进行。

我来回复

您尚未登录,请登录后再回复。点此登录或注册