将文件内容复制到多维数组中
Coping a file content into a multidimensional array
我创建了一个c++应用程序,用于将文件的内容读取到数组中:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile.txt");
int a[3];
int counter = 0;
char s[10];
while (!myfile.eof())
{
myfile.getline(s, 10,';');
a[counter]=atoi(s);
counter++;
}
for (int i = 0 ; i<3 ; i++)
cout << a[i]<<endl;
cin.get();
}
如果我的文件是:
15;25;50
运行正常
我的问题是:如果我把文件改成:
15;25;50
12;85;22
如何读取所有文件到一个3*2数组?
您有两个分隔符,;
和换行符(n
),这使事情变得有点复杂。您可以读取完整的一行,然后拆分该行。我还建议使用std::vector
而不是普通数组
std::vector<std::vector<int> > a;
std::string line;
while (std::getline(myfile, line)) {
std::vector<int> v;
std:istringstream ss(line);
std::string num;
while (std::getline(ss, num, ';')) {
int n = atoi(num);
v.push_back(n);
}
a.push_back(v);
}
也可以使用普通数组。然后,您必须确保,当您的行数超过数组允许时,您不会覆盖该数组。
如果你总是在一行中有三个数字,你也可以利用这一点,在;
拆分前两个数字,在n
拆分第三个数字
int a[2][3];
for (int row = 0; std::getline(myfile, s, ';'); ++row) {
a[row][0] = atoi(s);
std::getline(myfile, s, ';'));
a[row][1] = atoi(s);
std::getline(myfile, s));
a[row][2] = atoi(s);
}
但是这当然会失败,如果您在一行中有三个以上的数字,或者更糟糕的是,有两个以上的数字。
相关文章:
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 将字符数组复制到 QByte 数组中,而无需传递指针
- std::transform 将一个结构数组复制到另一个结构数组
- 如何使用指针C++将元素从2D数组复制到1D数组
- 如何将 int4 数组复制到 int8 向量中
- 如何将多维字符数组复制到字符 * 中
- std::将三维数组复制到三维向量中
- 为什么我不能将 C 样式数组复制到 std::array?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 为什么当我想将(使用 memcpy)结构数组复制到字符数组时,字符数组为空
- 如何将数据从数组复制到C++特征矩阵或向量
- 将数组复制C++作为特征矩阵的向量
- 如何在 c++ 中将数组复制到文件
- 如何将对象数组作为构造函数中的参数传递,然后将传递的数组复制到另一个数组(仍在构造函数中)
- CUDA 将大于线程计数的数组复制到共享内存
- 可以使用 std::copy 将 3D 数组复制到矢量
- 如何在C++中将本地字符串数组复制到私有成员字符串数组
- 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较