gpt4 book ai didi

c++ - 有人可以帮助我解决有关 C 中动态结构数组的编码问题吗?

转载 作者:太空狗 更新时间:2023-10-29 21:24:00 24 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;

struct car
{
string make;
int year;
};

int main()
{
int n;
cin >> n;
car * pt = new car[n];
for (int i=0; i<n; i++)
{
getline(cin, pt[i].make);
cin >> pt[i].year;
}
for (int i=0; i<n; i++)
cout << pt[i].year << ' ' << pt[i].make << endl;
return 0;
}

当我输入的时候,我只能输入一个数字和一个字符串。然后程序显示一些零。它阻止我输入更多信息。谁能向我解释发生了什么以及如何在 C++ 中解决这个问题?谢谢!

最佳答案

尝试以下操作:

 for (int i=0; i<n; i++)
{
cin.clear();
cin.ignore();
getline(cin, pt[i].make);
cin >> pt[i].year;
}

原因是之后

cin >> pt[i].year;

当您输入一些“东西”作为 year 时,您按回车键。它将在 cin 流中留下 \n。你需要有 cin.ignore 来忽略那个 \n 字符。你可能会发现 basic_istream/ignore有用。

关于c++ - 有人可以帮助我解决有关 C 中动态结构数组的编码问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17051535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com