简体   繁体   English

从 c++ 中的 txt 文件中读取二维数组

[英]Read 2d array from txt file in c++

This is my code这是我的代码

#include<bits/stdc++.h>
    using namespace std;
    int main()
    {
        char arr1[10][10];
        cout <<"Reading Start" <<endl;
        ifstream rfile("test.txt");
        rfile.getline(arr1[10],10);
        int i,j;
        for(i=0;i<6;i++)
        {
        for(j=0;i<6;j++)
        {
          cout << arr1[i][j];
        }
        }
        cout <<"\nRead Done" <<endl<<endl;
        rfile.close();
    }

This is my test.txt file这是我的 test.txt 文件

0 4 7 0 0 0
4 0 0 5 3 0
7 0 0 0 6 0
0 5 3 0 0 2
0 3 4 0 0 2
0 0 0 2 2 0

I want to read this matrix but when using the above code then it shows core dumped output, can anyone give me a better solution to do this thing?我想阅读这个矩阵,但是当使用上面的代码时,它显示核心转储 output,谁能给我一个更好的解决方案来做这件事?

can anyone give me a better solution to do this thing?谁能给我一个更好的解决方案来做这件事?

A better alternative would be to use a 2D vector as shown below.更好的选择是使用如下所示的 2D vector The advantage of using a vector over an array is that you don't need to specify(know) the rows and columns beforehand.在数组上使用vector优点是您不需要事先指定(知道)行和列。 That is, the text input file can have as many rows and columns and there is no need to ask the user (or preallocate) how many rows and columns does the file have.也就是说,文本输入文件可以有尽可能多的行和列,并且不需要询问用户(或预分配)文件有多少行和列。 std::vector will take care of it as shown below. std::vector处理它,如下所示。

The below program uses a 2D std::vector for storing information(like integers values in this case) in 2D manner.以下程序使用 2D std::vector以 2D 方式存储信息(如本例中的整数值)。 After reading all the values from the file you can process the vector according to your needs.从文件中读取所有值后,您可以根据需要处理向量。 The program shown reads data( int values) from input.txt and store those in a 2D vector .所示程序从input.txt读取数据( int值)并将其存储在 2D vector中。 Also, this program works even if there are uneven number of columns.此外,即使列数奇数,该程序也能正常工作。 You can use the below program as a reference(starting point).您可以使用以下程序作为参考(起点)。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
    std::string line;
    int word;
    
    std::ifstream inFile("input.txt");
    
    //create/use a std::vector instead of builit in array 
    std::vector<std::vector<int>> vec;
    
    if(inFile)
    {
        while(getline(inFile, line, '\n'))        
        {
            //create a temporary vector that will contain all the columns
            std::vector<int> tempVec;
            
            std::istringstream ss(line);
            
            //read word by word(or int by int) 
            while(ss >> word)
            {
                //std::cout<<"word:"<<word<<std::endl;
                //add the word to the temporary vector 
                tempVec.push_back(word);
            }      
            //now all the words from the current line has been added to the temporary vector 
            vec.emplace_back(tempVec);
        }    
    }
    else 
    {
        std::cout<<"file cannot be opened"<<std::endl;
    }
    
    inFile.close();
    //now you can do the whatever processing you want on the vector

    //lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
    for(std::vector<int> &newvec: vec)
    {
        for(const int &elem: newvec)
        {
            std::cout<<elem<<" ";
        }
        std::cout<<std::endl;
    }
    return 0;
}

The output of the above program can be seen here .以上程序的output可以看这里 The input file through which int values are read is also given at the above mentioned link.上面提到的链接也给出了读取 int 值的输入文件。

Advantages of using vector使用矢量的优点

  1. You don't need to ask the user for the number of rows and columns in the input file.您无需询问用户输入文件中的行数和列数。 That is you don't have to fix(hardcode) the size of your array.那就是您不必修复(硬编码)数组的大小。

  2. The above program works even if there are uneven entries in any particular row.即使任何特定行中的条目不均匀,上述程序也能正常工作。

  3. std::vector takes care of memory management for you. std::vector为您处理 memory 管理。 So you don't have to use new and delete by yourself which needs more attention/care.(in case you're thinking of creating array on heap)所以你不必自己使用newdelete ,这需要更多的关注/关心。(如果你想在堆上创建数组)

Becuase there are so many possible solutions, let us just show some.因为有很多可能的解决方案,让我们只展示一些。

The basic difference is, if we know the dimensions of the array at compile time,so,if there arecompiletime constants, then we can still use a C-Style array, or better, a std::array .基本的区别是,如果我们在编译时知道数组的维度,那么,如果有编译时常量,那么我们仍然可以使用 C-Style 数组,或者更好的是std::array

If we do not know the dimesions of the source data array, then we need a dynamic container that can grow, for example a std::vector .如果我们不知道源数据数组的尺寸,那么我们需要一个可以增长的动态容器,例如std::vector

In allcases, we can use the index operator [] with a standard for loop or a range based for loop with references.在所有情况下,我们都可以将索引运算符 [] 与标准 for 循环或基于范围的带有引用的 for 循环一起使用。 There is no difference.没有区别。


Examples:例子:

C-Style array with standard for loops and index based access具有标准 for 循环和基于索引的访问的 C 样式数组

#include <iostream>
#include <fstream>

constexpr int NumberOfRows = 6;
constexpr int NumberOfColumns = 6;

int main() {

    // Open the sourcefile
    std::ifstream sourceFileStream{ "test.txt" };

    // And check, if it could be opened
    if (sourceFileStream) {

        // Define 2D array to hold all data and initialize it with all 0
        char array2D[NumberOfRows][NumberOfColumns]{};

        // Read the rows and columns from the source file
        for (int row = 0; row < NumberOfRows; ++row)
            for (int col = 0; col < NumberOfColumns; ++col)
                sourceFileStream >> array2D[row][col];

        // Debug output
        for (int row = 0; row < NumberOfRows; ++row) {
            for (int col = 0; col < NumberOfColumns; ++col)  std::cout << array2D[row][col] << ' ';
            std::cout << '\n';
        }
    }
    else std::cerr << "\nError: Could not open source file\n\n";
}

C-Style array with range based for loop and reference access基于范围的 C 样式数组 for 循环和引用访问

#include <iostream>
#include <fstream>

constexpr int NumberOfRows = 6;
constexpr int NumberOfColumns = 6;

int main() {

    // Open the sourcefile
    std::ifstream sourceFileStream{ "test.txt" };

    // And check, if it could be opened
    if (sourceFileStream) {

        // Define 2D array toholdall data and initialize it with all 0
        char array2D[NumberOfRows][NumberOfColumns]{};

        // Read the rows and columns from the source file
        for (auto& row : array2D)
            for (auto& col : row)
                sourceFileStream >> col;

        // Debug output
        for (const auto& row : array2D) {
            for (const auto& col : row) std::cout << col << ' ';
            std::cout << '\n';
        }
    }
    else std::cerr << "\nError: Could not open source file\n\n";
}

C++ std::array with range based for loop C++ std::array与基于范围的 for 循环

#include <iostream>
#include <fstream>
#include <array>

constexpr int NumberOfRows = 6;
constexpr int NumberOfColumns = 6;

int main() {

    // Open the sourcefile
    std::ifstream sourceFileStream{ "test.txt" };

    // And check, if it could be opened
    if (sourceFileStream) {

        // Define 2D array toholdall data and initialize it with all 0
        std::array<std::array<char, NumberOfColumns>, NumberOfRows> array2D{};

        // Read the rows and columns from the source file
        for (auto& row : array2D)
            for (auto& col : row)
                sourceFileStream >> col;

        // Debug output
        for (const auto& row : array2D) {
            for (const auto& col : row) std::cout << col << ' ';
            std::cout << '\n';
        }
    }
    else std::cerr << "\nError: Could not open source file\n\n";
}

Dynamic solution, with a std::vector动态解决方案,带有std::vector

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

int main() {

    // Open the sourcefile
    std::ifstream sourceFileStream{ "test.txt" };

    // And check, if it could be opened
    if (sourceFileStream) {

        // Define 2D array to hol dall data and initialize it with all 0
        std::vector<std::vector<char>> array2D{};

        // Read the rows and columns from the source file
        std::string line{};
        while (std::getline(sourceFileStream, line)) {

            // Add a new row to our matrix
            array2D.push_back(std::vector<char>{});

            // Read all column data
            char c{};
            for (std::istringstream iss(line); iss >> c; array2D.back().push_back(c))
                ;
        }
        // Debug output
        for (const auto& row : array2D) {
            for (const auto& col : row) std::cout << col << ' ';
            std::cout << '\n';
        }
    }
    else std::cerr << "\nError: Could not open source file\n\n";
}

Basically, everything is the same somehow.基本上,一切都是一样的。 . . . .

There are a lot of other ways to perform the specific task, but i guess your method is not wrong, and you have just made a simple typing mistake in your second for loop condition.还有很多其他方法可以执行特定任务,但我想你的方法没有错,而且你刚刚在第二个 for 循环条件中犯了一个简单的输入错误。 so ill just fix your code for you.所以我只是为你修复你的代码。 and also you could just input single values at a time as u go.你也可以一次只输入一个值作为u go。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    char arr1[10][10];
    cout <<"Reading Start" <<endl;
    ifstream rfile("test.txt");
    int i,j;
    for(i=0;i<6;i++){
        for(j=0;j<6;j++){
            rfile >> arr1[i][j];
            cout << arr1[i][j] << " ";
        }
        cout << endl;
    }

    cout <<"\nRead Done" <<endl<<endl;
    rfile.close();
}

Output: Output: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM