65,211
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using namespace std;
int main()
{
using namespace std;
struct car
{
string Manufacturer;
int ProductionYear;
};
cout << "How many cars do you wish to catalog ? ";
int n;
cin >> n;
cin.ignore(); //Here
car * cars = new car[n];
for(int i= 0;i < n; i++)
{
cout << "car #" << i + 1 << ":\n" << "please enter the make:";
getline(cin,cars[i].Manufacturer); // 执行到此处,未等待输入,直接执行下一行,为什么?
cout << "please enter the year made:";
cin >> cars[i].ProductionYear;
cin.ignore(); //Here
};
cout << "Here is your collection:\n";
for(int i= 0;i < n; i++)
cout << cars[i].ProductionYear << "\t" << cars[i].Manufacturer << endl;
};
//cin.ignore()这个方法用于将cin对象中缓冲区的部份字符丢弃,缺省状态是丢一个字符
//这个地方丢弃了你的回车符
#include "stdafx.h"
#include <iostream>
#include <string>
int main()
{
using namespace std;
struct car
{
string Manufacturer;
int ProductionYear;
};
cout << "How many cars do you wish to catalog ? ";
int n;
cin >> n;
car * cars = new car[n];
for(int i= 0;i < n; i++)
{
cout << "car #" << i + 1 << ":\n" << "please enter the make:";
getchar();getchar();
getline(cin,cars[i].Manufacturer); // 执行到此处,未等待输入,直接执行下一行,为什么?
cout << "please enter the year made:";
cin >> cars[i].ProductionYear;
};
cout << "Here is your collection:\n";
for(i= 0;i < n; i++)
cout << cars[i].ProductionYear << "\t" << cars[i].Manufacturer << endl;
};