如何编辑结构数组中的变量

How do I go about editing the variables in a struct array?

本文关键字:数组 变量 结构 何编辑 编辑      更新时间:2023-10-16

我在谷歌上搜索过,询问过我的同学,最后还向我的教授询问过这个特定的问题,但我还没有找到解决方案。我希望这里有人能帮我。

基本上,我需要制作一个结构数组,每个结构包含4条信息:国家名称、国家人口、国家地区和国家密度。这些信息将从.txt文档写入数组中的结构。然后,这些信息将从所述阵列写入控制台。

不幸的是,在尝试向数组中的structs写入任何内容时,我遇到了2个错误。"无法从'const char[8]'转换为'char[30]'"并且"没有运算符'[]'与这些操作数匹配,操作数类型为:CountryStats[int]"。这两个错误都涉及以下行:

countries[0].countryName = "A";

请记住,我刚开始使用structs,这是我第一次在数组中使用它们。此外,我必须使用数组,而不是向量。

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
struct CountryStats;
void initArray(CountryStats *countries);
const int MAXRECORDS = 100;
const int MAXNAMELENGTH = 30;
struct CountryStats
{
char countryName[MAXNAMELENGTH];
int population;
int area;
double density; 
};
// All code beneath this line has been giving me trouble. I need to easily edit the 
// struct variables and then read them.
int main(void)
{
CountryStats countries[MAXRECORDS];
initArray(*countries);
}
void initArray(CountryStats countries)
{
countries[0].countryName = "A";
}

到目前为止,我只是试图弄清楚如何将信息写入数组中的结构,然后将其中的信息读取到控制台上。在我找到解决方案后,其他一切都应该到位。

哦,还有最后一点:我还没有完全学会指针(*)的功能。我对C++还是比较陌生的,因为我过去的编程教育主要是用Java。在解决这个问题的过程中,这段代码中包含的任何指针都受到了我的同学和教授的影响。

提前感谢!

的两个问题

void initArray(CountryStats countries)

必须是:

void initArray(CountryStats *countries)

您必须使用strcpy来复制c样式的字符串。(但我建议使用c++字符串而不是char[])

strcpy(countries[0].countryName,"A");

但我再说一遍,使用c++功能,如vector<>和字符串。

您没有为定义

void initArray(CountryStats *countries);

但适用于:

void initArray(CountryStats countries);

其中CCD_ 1不是阵列。由于没有为CountryStats定义operator[],因此表达式countries[0]无法编译。

由于您不能使用std::vector(出于一些奇怪的原因),我建议您使用std::array:

template<std::size_t N>
void initArray(std::array<CountryStats, N>& ref) {
for (std::size_t i = 0; i < N; i++)
// initialize ref[i]
}

当然,如果你觉得受虐,你也可以使用C型数组:

void initArray(CountryStats* arr, int size) {
for (int i = 0; i < size; i++)
// initialize arr[i]
}

但是,您可能需要提供数组的维度作为第二个参数。