请各位前辈指导

443692487 2012-07-18 03:31:04
我在vc6.0里面输入这个程序,为什么运行结果总是不对呢
#include "iostream"
#include "string"
using namespace std;
struct Car{
string maker;
int year;
};
int main(){
int count;
cout<<"How many cars do you wish to catalog? ";
cin>>count;
Car *car;
car = new Car[count];
for (int i = 0;i<count;i++){
cout<<"car #"<<(i+1)<<":"<<endl;
cout<<"Please enter the maker : ";
getline(cin,car[i].maker);
cout<<"Please enter the year made: ";
cin>>car[i].year;
cout<<endl;
}
cout<<"Here is your collection : "<<endl;
for (int j = 0;j<count;j++){
cout<<car[j].year<<"\t"<<car[j].maker<<endl;
}
delete []car;
return 0;

}
...全文
102 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
443692487 2012-07-18
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]
getline之前加入
cin.ignore();
抛弃原来cin缓冲区中的内容。
[/Quote]
加上这个运行也对,为什么要抛弃原来缓冲区的内容啊,原来的缓冲区会对getlin()造成影响么?
为什么改成char maker[20];cin>>car[i].maker就不需要抛弃原来缓冲区内容啊?我是c++新手,谢谢了啊
443692487 2012-07-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]
cout<<"car #"<<(i+1)<<":"<<endl;
cout<<"Please enter the maker : ";
getchar();
getline(cin,car[i].maker);
cout<<"Please enter the year made: ";
cin>>car[i].year;
cout<<endl;

加上红色的那句看看吧。。
[/Quote]加上getchar()确实行的,但是为什么要加上这个啊?能不能讲讲原理呀
微型蚂蚁 2012-07-18
  • 打赏
  • 举报
回复
getline之前加入
cin.ignore();
抛弃原来cin缓冲区中的内容。
wZi 2012-07-18
  • 打赏
  • 举报
回复
抑或


cout<<"How many cars do you wish to catalog? ";
cin>>count;

fflush(stdin);
443692487 2012-07-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
不对的意思是啥????
[/Quote]
我也说不清楚,你看看程序,比如说getline(cin,car[i].maker);当输入的字符串里面包括空格时就会出现异常,和预期的不一样啊,不知道为什么我一碰到string类就出错,把string maker改成char maker[20];就对了
wZi 2012-07-18
  • 打赏
  • 举报
回复
cout<<"car #"<<(i+1)<<":"<<endl;
cout<<"Please enter the maker : ";
getchar();
getline(cin,car[i].maker);
cout<<"Please enter the year made: ";
cin>>car[i].year;
cout<<endl;

加上红色的那句看看吧。。
wZi 2012-07-18
  • 打赏
  • 举报
回复
不对的意思是啥????

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧