从2d整数数组中读取文件

问题描述 投票:-2回答:1

我是c ++编码的新手,我需要从这个结构的文件中读取:

8
1 0 0 0 1
1 1 1 0 0
1 1 0 0 0
1 1 1 1 0
5

我需要将数字读入2个不同的int变量(8和5),其余的在2d int数组中。

到目前为止我有什么:

#include<fstream>
#include<iostream>
#include<conio.h>

using namespace std;

ifstream fin("f.in");
ofstream gout("g.out");

int a[30][30], n, x;

int main()
{
    fin>>n;

    for(i=1; i<=n; i++)
        for(j=1; j<=n; j++)
        {
            fin>>a[i][j];

        }
    fin>>x; c[1]=x; s[x]=1;
//other function call .....

    for(i=1; i<=n; i++)
        gout<<c[i]<<" ";

    return 0;
}

代码正在构建和编译,但是它不会从文件中读取。

c++
1个回答
0
投票

如果你仍然陷入困境,那就让我们一步一步来。

首先不要硬编码文件名。 (并且不要使用魔术数字,例如代码中的任何数字,而不是为其正确定义常量)。 ifstream fin("f.in");如果您想要阅读另一个文件"f.int2"怎么办?这就是函数参数的用途。对于main(),你有argc告诉你有多少参数,argv,一个指向每个args的指针数组(后面跟着一个终止的NULL指针)。使用它们。例如:

int main (int argc, char **argv) {
...
    if (argc < 2) { /* validate 1-argument available for filename */
        std::cerr << "error: insufficnent input\nusage: " << argv[0]
                << " filename\n";
        return 1;
    }

    std::ifstream fin (argv[1]);    /* open filename given by 1st argument */

(注意:第一个参数值argv[0]始终是正在运行的可执行文件名,因此您必须检查总共两个参数以确保argv[1]中存在某些内容)

接下来验证文件是否已打开以供阅读,例如

    if (!fin.good()) {  /* validate file open for reading */
        std::cerr << "error: file open failed '" << argv[1] << "'.\n";
        return 1;
    }

现在让我们来阅读你的输入文件,我将命名为2dintarr+stuff.txt,我将它放在dat子目录中,例如

示例输入文件

$ cat dat/2dintarr+stuff.txt
8
1 0 0 0 1
1 1 1 0 0
1 1 0 0 0
1 1 1 1 0
5

"+stuff"85,与您想要存储的2D数组值无关。 85很容易通过将整行读入string,从行创建一个stringstream,然后从stringstream循环和读取整数直到你用完数字来阅读来轻松处理。如果您在数字用完之前只读取了一个值,那么您可以将这些值存储在不是数组的某个位置(例如在名为notarr的向量中)。如果行中有多个值,则将所有值存储在向量中,并将该向量作为向量的向量中的行添加。

听起来很复杂,但事实并非如此。 C ++提供容器,允许您像添加数组一样向它们添加和删除值,但更好的是,容器会自动为您管理内存,根据需要分配更多内容,并在没有更多引用时释放内存。容器。其中一个容器是vector,您可以将其视为一维数组。 C ++允许容器包含其他容器。因此,当您需要2D数组时,您想要的是矢量矢量。

在你的情况下你需要一个string来保存你读取的每一行数据,你需要你的数组矢量arr矢量,然后另一个单一的矢量来保存不属于你的数组的"+stuff" - 称为notarr。声明如下:

#include <string>
#include <vector>
...
    std::string line;                       /* string for reading each line */
    std::vector<std::vector <int>> arr;     /* vector<vector<int>> (2D arr) */
    std::vector<int> notarr;                /* vector to hold single values */

现在剩下的就是读取每一行,然后从该行创建一个字符串流,这样你就可以从行中循环读取整数,直到你的数字用完为止。 (你不能只是在一个循环中使用fin >> number;,因为读取iostream将跳过前导空格,'\n'是空白,所以试图在文件流本身上使用>> - 你永远无法分辨出行中有多少值,>>只会跳过'\n'作为空格。

如何解决?使用stringstream。基本上,字符串流相当于可以用作流的缓冲区。所以你从文件中读取一行数据,从中创建一个字符串流,然后循环while (ss >> value),当它到达字符串流的末尾(即缓冲区)时将停止,因为没有其他内容可供读取,允许您确定有多少值包含在原始行中。 (你会反复使用这种技术)

例:

    while (getline (fin, line)) {  /* read each remaining data line */
        int i;
        std::vector<int> tmp;           /* vector<int> for each line */
        std::stringstream ss (line);    /* stringstream to read from */
        while (ss >> i)                 /* read int from stringstream */
            tmp.push_back(i);           /* add to tmp vector */
        if (tmp.size() == 1)            /* if single value in line */
            notarr.push_back(i);        /* add value to notarr */
        else if (tmp.size() > 1)        /* if multiple values in line */
            arr.push_back(tmp);         /* add tmp vector to arr */
    }

在上面你只需将每行读入line,创建stringsteam ss,然后使用临时向量tmp,将每个值加载到临时向量中。完成后,您只需检查tmp向量中有多少元素。如果一个,它是85,将它添加到矢量notarr,如果它不止一个,tmp包含你的2D数组的一行,所以添加它做arr。而已。

完全放在一起,你可以这样做:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <limits>

int main (int argc, char **argv) {

    std::string line;                       /* string for reading each line */
    std::vector<std::vector <int>> arr;     /* vector<vector<int>> (2D arr) */
    std::vector<int> notarr;                /* vector to hold single values */

    if (argc < 2) { /* validate 1-argument available for filename */
        std::cerr << "error: insufficnent input\nusage: " << argv[0]
                << " filename\n";
        return 1;
    }

    std::ifstream fin (argv[1]);    /* open filename given by 1st argument */
    if (!fin.good()) {  /* validate file open for reading */
        std::cerr << "error: file open failed '" << argv[1] << "'.\n";
        return 1;
    }

    while (getline (fin, line)) {  /* read each remaining data line */
        int i;
        std::vector<int> tmp;           /* vector<int> for each line */
        std::stringstream ss (line);    /* stringstream to read from */
        while (ss >> i)                 /* read int from stringstream */
            tmp.push_back(i);           /* add to tmp vector */
        if (tmp.size() == 1)            /* if single value in line */
            notarr.push_back(i);        /* add value to notarr */
        else if (tmp.size() > 1)        /* if multiple values in line */
            arr.push_back(tmp);         /* add tmp vector to arr */
    }

    std::cout << "2D array of values:\n\n";
    for (auto& i : arr) {           /* loop over rows */
        for (auto& j : i)           /* loop over each value in column */
            std::cout << " " << j;  /* output value */
        std::cout << '\n';          /* tidy up with newline */
    }

    std::cout << "\nSingle-values:\n\n";
    for (auto& i: notarr)           /* output values not part of array */
        std::cout << " " << i;      
    std::cout << '\n';              /* tidy up with newline */
}

(注意:向量容器提供了.push_back().size()成员函数,允许您向向量添加值并告诉您分别包含许多元素。)

示例使用/输出

$ ./bin/rd2dintarr+stuff dat/2dintarr+stuff.txt
2D array of values:

 1 0 0 0 1
 1 1 1 0 0
 1 1 0 0 0
 1 1 1 1 0

Single-values:

 8 5

仔细看看,如果您有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.