【问题标题】:Coping a file content into a multidimensional array将文件内容复制到多维数组中
【发布时间】:2012-12-27 13:39:48
【问题描述】:

我创建了一个 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 数组?

【问题讨论】:

  • 好吧,我找不到任何方法:(
  • 1.使用std::string,而不是字符数组和std::vector,而不是在文件中有超过三行时溢出的数组。 2. 使用while (getline()),而不是while (!eof())。 3. 使用stoi 代替atoi 之类的东西,这绝对无法判断这是不是一个错误。 4. 更喜欢std::whatever 而不是using namespace std;
  • 那么,您认为您需要做什么?如何定义一个 3 x 2 矩阵(二维数组)?
  • @Mats Petersson ,我将使用 int b[3][2] 定义它,我知道如何使用数组,问题是我找不到任何方法将文件内容复制到其中。
  • 它遵循与您当前相同的方式。每行都需要一个循环...

标签: c++ file-io multidimensional-array


【解决方案1】:

您有两个分隔符,; 和换行符 (\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);
}

但这当然会失败,如果您连续有超过三个数字,或者更糟糕的是,有超过两行。

【讨论】:

  • 您可以使用stringstream 将字符串转换为int 而不是atoi(),因为除此之外您的代码完全是C++。
  • 或使用 stoi(),它将 std::string 作为 arg。
  • @prajmus 你是对的,这个或使用std::stoi 将是另一个改进。另一方面,如果您的输入中只有数字,atoi 也不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2013-10-08
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多