![](/img/trans.png)
[英]In C++, how do I go about turning different lines of a txt file into multiple variables?
[英]How do I go about editing the variables in a struct array?
我已经用Google搜索了,问了我的同学,最后问了我的教授关于这个特殊问题的信息,但是我还没有找到解决方案。 我希望这里有人可以帮助我。
基本上,我需要构建一个结构数组,每个结构包含4条信息:国家/地区名称,国家/地区人口,国家/地区和国家/地区密度。 此信息将从.txt文档写入数组中的结构。 然后,该信息将从所述阵列写入控制台。
不幸的是,在尝试向数组中的结构写入任何内容时,我遇到了2个错误。 “无法从'const char [8]'转换为'char [30]'”,并且“没有运算符'[]'与这些操作数匹配,操作数类型为:CountryStats [int]”。 这些错误均引用该行:
countries[0].countryName = "A";
请记住,我只是开始使用结构,这是我第一次在数组中使用它们。 另外,我必须使用数组,而不是向量。
这是我的代码:
#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);
在哪个countries
不是数组。 由于没有为CountryStats
定义operator[]
,因此表达式CountryStats
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]
}
但是,您可能需要提供数组的维数作为第二个参数。
两个问题
void initArray(CountryStats countries)
一定是:
void initArray(CountryStats *countries)
并且您必须使用strcpy复制c样式字符串。 (但我建议使用c ++字符串代替char [])
strcpy(countries[0].countryName,"A");
但是我再说一遍,使用c ++功能,例如vector <>和string。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.