如何编辑结构数组中的变量
How do I go about editing the variables in a struct array?
我在谷歌上搜索过,询问过我的同学,最后还向我的教授询问过这个特定的问题,但我还没有找到解决方案。我希望这里有人能帮我。
基本上,我需要制作一个结构数组,每个结构包含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]
}
但是,您可能需要提供数组的维度作为第二个参数。
- 具有推导参数的模板函数指针数组变量
- 按字母顺序对结构内数组变量中的名称进行排序
- 传递 std::数组变量作为参数
- 为什么数组变量正在更新
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 数组变量中更多变量或更多维度?
- 数组变量周围的堆栈已损坏
- 数组变量衰减为指针
- C++ 无法将字符数组变量分配给字符串变量
- 使用指针变量打印特定的数组变量
- 数组变量是C++中的引用吗?
- 数组变量未正确分配以进行循环
- 在 c++ 中向数组变量添加一个数字
- 如果数组变量在 c# 代码中定义为“ref”参数,则如何传递数组变量
- 指针和 c 样式数组变量的专用模板
- 堆栈数组变量清理
- 如何从DLL检索数组变量?(视觉C )
- 如何将初始值设定项与右值引用参数一起使用 // 为什么不能使用另一个 C 样式数组变量初始化 C 样式数组
- 更改了错误的数组变量