gpt4 book ai didi

c++ - 如何使用动态大小的结构数组?

转载 作者:太空狗 更新时间:2023-10-29 23:07:35 25 4
gpt4 key购买 nike

我得做作业了。它是控制台应用程序,它使用一组结构来保存有关计算机的信息(品牌、制造年份、重量和库存编号)。所以我写了一个完整的工作程序,但我想使用动态数组,因为我不知道用户将输入多少条记录。

有没有办法做到这一点。要在数组中添加新记录直到用户说 n/N?有什么建议吗?

这是我的程序版本:

#include "stdafx.h"
#include <iostream>

using namespace std;

struct ComputerInfo
{
char computerMark[20], invertarNumber[6];
unsigned int year;
float weight;
};

ComputerInfo computerArray[300];

ComputerInfo AddComputers(ComputerInfo compterArray[], int counter)
{
cout << "Enter mark of the computer: ";
cin >> computerArray[counter].computerMark;

cout << "Enter year of establish: ";
cin>> computerArray[counter].year;

while ((computerArray[counter].year < 1973)
|| (computerArray[counter].year > 2013))
{
cout << "INVALID YEAR!!!" << endl;

cout << "Enter year of establish: ";
cin>> computerArray[counter].year;
}

cout << "Enter computer weidth: ";
cin >> computerArray[counter].weight;

cout << "Enter computer invertar number(up to six digits): ";
cin >> computerArray[counter].invertarNumber;

return computerArray[counter];
}

void ShowRecords()
{
int counter = 0;

while (computerArray[counter].year != 0)
{
cout << "Mark: " << computerArray[counter].computerMark << endl;
cout << "Year: " << computerArray[counter].year << endl;
cout << "Weidth: " << computerArray[counter].weight << endl;
cout << "Inv. number: " << computerArray[counter].invertarNumber << endl << endl;

counter++;
}
}

void MoreThanTenYearsOld(ComputerInfo computerArray[])
{
int counter = 0;
float counterOldComputers = 0;
float computerPer = 0;

while (computerArray[counter].year == 0)
{
if (computerArray[counter].year <= 2003)
{
counterOldComputers++;
}

counter++;
}

computerPer = counterOldComputers / 3;

cout << endl;
cout << "Percantage of old computers is: " << computerPer << endl;
}

int main()
{
int counter = 0;
float computerPer = 0;
char answer = 'y';

for (int i = 0; i <= 299; i++)
{
strcpy(computerArray[i].computerMark,"");
}

while((answer == 'Y') || (answer == 'y'))
{
computerArray[counter] = AddComputers(computerArray, counter);
cout << endl;
cout << "Do you want to enter more records (Y/N): ";
cin >> answer;
cout << endl;
counter++;
}

MoreThanTenYearsOld(computerArray);

return 0;
}

最佳答案

是的。而不是你的阵列,使用

std::vector<ComputerInfo> computerArray;

您可以根据需要添加任意数量的对象:

ComputerInfo c;
// read the data
computerArray.push_back(c);

现在,computerArray[0]将在 c 中获得信息.

您需要 #include <vector> .

此外,而不是 char computerMark[20]你可以使用 std::string .

关于c++ - 如何使用动态大小的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12352783/

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