将数据从文件读入数组 [英] Reading data from file into array
问题描述
我试图将某个文件中的特定数据读取到两个2D数组中。第一行数据定义每个数组的大小,所以当我填充第一个数组时,我需要跳过那一行。跳过第一行后,第一个数组填充文件中的数据,直到文件中的第7行。第二个数组用来自文件的其余数据填充。
以下是我的资料档案的标签图片:
这里是我的(有缺陷的)代码:
#include< fstream>
#include< iostream>
using namespace std;
int main()
{
ifstream inFile;
int FC_Row,FC_Col,EconRow,EconCol,seat;
inFile.open(Airplane.txt);
inFile>> FC_Row>> FC_Col>> EconRow>> EconCol;
int firstClass [FC_Row] [FC_Col];
int economyClass [EconRow] [EconCol];
//感谢junjanes
for(int a = 0; a for(int b = 0; b inFile>> firstClass [a] [b];
for(int c = 0; c for(int d = 0; d inFile> economyClass [c] [d];
系统(PAUSE);
return EXIT_SUCCESS;感谢您输入所有人。
c>循环迭代,直到文件结束,你不需要它们。 $ b
$ b while(inFile>> seat)//读取直到飞机结束。
改用(不带 while
):
for(int a = 0; a< FC_Row; a ++)//读取此行数。
for(int b = 0; b inFile>> firstClass [a] [b]; //在这里读下一个座位。
适用于经济型座位。
也可以将数组变成向量,因为可变大小的数组是地狱。
vector< vector< int> > firstClass(FC_Row,vector< int>(FC_Col));
vector< vector< int> > economyClass(EconRow,vector< int>(EconCol));
您需要 #include< vector>
使用向量,它们的访问权限与数组相同。
I am trying to read specific data from a file into two 2D arrays. The first line of data defines the size of each array so when I fill the first Array i need to skip that line. After skipping the first line, the first array fills with data from the file until the 7th line in the file. The second array is filled with the rest of the data from the file.
Here's a labeled image of my data file:
and here's my (flawed) code so far:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream inFile;
int FC_Row, FC_Col, EconRow, EconCol, seat;
inFile.open("Airplane.txt");
inFile >> FC_Row >> FC_Col >> EconRow >> EconCol;
int firstClass[FC_Row][FC_Col];
int economyClass[EconRow][EconCol];
// thanks junjanes
for (int a = 0; a < FC_Row; a++)
for (int b = 0; b < FC_Col; b++)
inFile >> firstClass[a][b] ;
for (int c = 0; c < EconRow; c++)
for (int d = 0; d < EconCol; d++)
inFile >> economyClass[c][d] ;
system("PAUSE");
return EXIT_SUCCESS;
}
Thanks for the input everyone.
解决方案 Your while
loops iterate until the end of file, you don't need them.
while (inFile >> seat) // This reads until the end of the plane.
Use instead (without the while
):
for (int a = 0; a < FC_Row; a++) // Read this amount of rows.
for (int b = 0; b < FC_Col; b++) // Read this amount of columns.
inFile >> firstClass[a][b] ; // Reading the next seat here.
Apply the same for economic seats.
Also you might want change arrays into vectors, since variable size arrays are hell.
vector<vector<int> > firstClass(FC_Row, vector<int>(FC_Col)) ;
vector<vector<int> > economyClass(EconRow, vector<int>(EconCol)) ;
You need to #include <vector>
to use vectors, their access is identical to arrays.
这篇关于将数据从文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文