将文件的列读入数组
Reading file's columns into array
我正在读取具有一定列数的文件,每行都有不同数量的列,它们是不同长度的数值,并且我有固定的行数(20)如何将每一列放入数组中?
假设我有如下数据文件(每列之间有选项卡)
20 30 10
22 10 9 3 40
60 4
30 200 90
33 320 1 22 4
如何将这些列放入不同的数组中,该列 1 转到一个 arrary,第 2 列转到另一个 arrary。只有第 2 列的值超过 2 位,其余列的值超过 1 位或两位,并且某些列也为 null,但 1、2 和 3 除外
int main()
{
ifstream infile;
infile.open("Ewa.dat");
int c1[20], c2[20], ... c6[20];
while(!infile.eof()) {
//what will be the code here?
infile >>lines;
for(int i = 1; i<=lines; i++) {
infile >> c1[i];
infile >> c2[i];
.
.
infile >> c6 [20];
}
}
}
这是主要思想:
使用 2D 数组而不是许多 1D 数组。
使用 std::string
读取每一行。
然后使用: istringstream is(str);
这将有助于解析字符串并放入数组中,如下所示:
while(...) {
....
getline(infile, str);
istringstream is(str);
j=0;
while(is)
{
is >> c[i][j];
}
i++;
....
}
剩下的就交给你了。
利用
一些C++库类可能更容易,如std::vector
、std::istringstream
和std::string
:
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
std::vector<std::vector<int> > allData;
std::ifstream fin("data.dat");
std::string line;
while (std::getline(fin, line)) { // for each line
std::vector<int> lineData; // create a new row
int val;
std::istringstream lineStream(line);
while (lineStream >> val) { // for each value in line
lineData.push_back(val); // add to the current row
}
allData.push_back(lineData); // add row to allData
}
std::cout << "row 0 contains " << allData[0].size() << " columnsn";
std::cout << "row 0, column 1 is " << allData[0][1] << 'n';
}
相关文章:
- 如何将内容数组写入文本文件?
- C++将文本文件中的数据读取到结构数组中
- 将值从二维数组输出到文本文件
- C++数据文件、数组和计算赋值
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从txt文件中读取多个不同长度的数组?
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- C++编程从外部文本文件定义数组大小
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 将系数存储在头文件的数组中("does not name a type"错误)
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 从文件读取,并写入函数C++中的数组
- 如何从具有两列的.txt文件创建并行数组?
- 读取二维数组文件