C++ 从混合数据文件读取将项添加到字符串数组和二维整数数组C++;
我有一个如下所示的文本文件:C++ 从混合数据文件读取将项添加到字符串数组和二维整数数组C++;,c++,arrays,C++,Arrays,我有一个如下所示的文本文件: January 35 45 February 45 55 etc... 我试图通读该文件并将每个月添加到字符串数组中,然后将下面的每个整数添加到二维数组中 我有一个月[]数组和一个临时[]数组 我正在尝试这样的事情 int size = 0; while(!file.eof()) { file >> months[size]; size++; } 我不知道如何将这两个整数添加到int数组中 这对于一个类来说
January 35 45
February 45 55
etc...
我试图通读该文件并将每个月添加到字符串数组中,然后将下面的每个整数添加到二维数组中
我有一个月[]数组和一个临时[]数组
我正在尝试这样的事情
int size = 0;
while(!file.eof()) {
file >> months[size];
size++;
}
我不知道如何将这两个整数添加到int数组中
这对于一个类来说,出乎意料的是,要求特别是从文件中读取数据,并将月份插入数组,将下面两个整数插入二维数组
我们还没有研究过结构或向量 不要使用数组。具有结构的模型
struct Month_Record
{
std::string month_name;
int value_1;
int value_2;
};
接下来,添加一个方法来输入结构:
struct Month_Record
{
//... same as above
friend std::istream& operator>>(std::istream& input, Month_Record& mr);
}
std::istream& operator>>(std::istream& input, Month_Record& mr)
{
input >> mr.month_name;
input >> mr.value_1;
input >> mr.value_2;
return input;
}
您的输入变成:
std::vector<Month_Record> database;
Month_Record mr;
while (input_file >> mr)
{
database.push_back(mr);
}
std::向量数据库;
月记录;
while(输入文件>>mr)
{
数据库。推回(mr);
}
您可以像访问阵列一样访问数据库:
std::cout << database[0].month_name
<< ", " << database[0].value_1
<< ", " << database[0].value_2
<< "\n";
std::cout
您可能需要在循环结束后进行测试,以确保所有数据都已读取。如果要读取到文件的末尾,则类似于If(file.eof())
的内容将确保读取了整个文件。如果您想要一年的数据,If(size==ONE_year)
其中ONE_year
是一个常数,定义了一年中的月数。可能的重复:这将很有帮助,。这是针对一个类的,具体要求是使用并行数组和二维数组。@BenGrzybowski做你必须做的事情来通过课程,但这是正确的方法。
int size = 0;
while(size < MAX_ARRAY_LENGTH && // prevent overflow.
// Will stop here if out of space in array
// otherwise && (logical AND) will require the following be true
file >> months[size] // read in month
>> temps[size][0] // read in first temp
>> temps[size][1]) // read in second temp
{ // if the month and both temperatures were successfully read, enter the loop
size++;
}
loop
if array has room
read all required data from stream
if all data read
increment size
go to loop.