将文件内容复制到多维数组中

Coping a file content into a multidimensional array

本文关键字:数组 复制 文件      更新时间:2023-10-16

我创建了一个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);
}

但是这当然会失败,如果您在一行中有三个以上的数字,或者更糟糕的是,有两个以上的数字。