#include <iostream>
using namespace std;
int main()
{
struct Car
{
char maked[20];
int year;
};
unsigned int i;
cout << "How many cars do you wish to catalog ? ";
cin >> i;
Car *car = new Car[i];
for (int k = 0; k < i; k++)
{
cout << "Car #" << k + 1 << ":" << endl;
cout << "Please enter the make : ";
cin.getline(car[k].maked,20);
//cin.get();
cout << "Please enter the year made: ";
//cin.get();
cin>> car[k].year;
cin.get();
}
cout << "Here is your collection : " << endl;
for (int k = 0; k < i; k++)
{
cout << car[k].year << "\t" << car[k].maked << endl;
}
delete[]car;
return 0;
}
为什么for循环内的第一次不让输入字符串啊?
这个问题我今天在学习 C++ 的时候也遇到了,这个问题的原因是因为 cin 在读取年份的时候,将回车键生成的换行符留在了输入队列中。
问题是以下这行代码。
cout << "How many cars do you wish to catalog ? ";
cin >> i;
输入这行之后我们是按了 键换行符的,所以这个换行符被读取进了下面的 cin.getline(...),相当于 cin.getline(...) 读取了一个 。
同样下面的循环内部的cin 也一样,**要解决 这个的办法就是在每次输入数字的后面加上代码 cin.get();** 这样子就能把输入的 保存在 cin.get()里面了。
下面是我自己打的代码,我测试了是可以用的
#include <iostream>
using namespace std;
struct car
{
string production;
int proYear;
};
int main()
{
int c_num;
cout << "This program will show up your collection, my Lord" << endl;
cout << "How many cars do you wish to catalog? ";
cin >> c_num;
cin.get();
car * collect = new car [c_num];
for (int i = 0; i < c_num; ++i) {
cout << "Please enter the make: ";
getline(cin, (collect + i)->production);
cout << "Please enter the year made: ";
cin >> ((collect + i)->proYear);
cin.get();
}
cout << "Here is your collection: " << endl;
for (int i = 0; i < c_num; ++i) {
cout << (collect + i)->proYear << " " << (collect + i)->production << endl;
}
delete [] collect;
return 0;
}
希望能帮到你!
unsigned int i;
cout << "How many cars do you wish to catalog ? ";
cin >> i;
第一次是输入到i吧,i不是整形么?
因为你的代码写的是第一个输入的是一个int类型数据,如果要输入字符的话也能接收进去,只不过里面的内容可能不是你预期的
你在每个scanf后面,都加个getchar()后试试效果
上面那个回复错了,你在第一次进for循环的时候,在for循环里打个断点看下maked字符数组里是不是已经有内容了