簡體   English   中英

從 c++ 中的 txt 文件中讀取二維數組

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

這是我的代碼

#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();
    }

這是我的 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

我想閱讀這個矩陣,但是當使用上面的代碼時,它顯示核心轉儲 output,誰能給我一個更好的解決方案來做這件事?

誰能給我一個更好的解決方案來做這件事?

更好的選擇是使用如下所示的 2D vector 在數組上使用vector優點是您不需要事先指定(知道)行和列。 也就是說,文本輸入文件可以有盡可能多的行和列,並且不需要詢問用戶(或預分配)文件有多少行和列。 std::vector處理它,如下所示。

以下程序使用 2D std::vector以 2D 方式存儲信息(如本例中的整數值)。 從文件中讀取所有值后,您可以根據需要處理向量。 所示程序從input.txt讀取數據( int值)並將其存儲在 2D vector中。 此外,即使列數奇數,該程序也能正常工作。 您可以使用以下程序作為參考(起點)。

#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;
}

以上程序的output可以看這里 上面提到的鏈接也給出了讀取 int 值的輸入文件。

使用矢量的優點

  1. 您無需詢問用戶輸入文件中的行數和列數。 那就是您不必修復(硬編碼)數組的大小。

  2. 即使任何特定行中的條目不均勻,上述程序也能正常工作。

  3. std::vector為您處理 memory 管理。 所以你不必自己使用newdelete ,這需要更多的關注/關心。(如果你想在堆上創建數組)

因為有很多可能的解決方案,讓我們只展示一些。

基本的區別是,如果我們在編譯時知道數組的維度,那么,如果有編譯時常量,那么我們仍然可以使用 C-Style 數組,或者更好的是std::array

如果我們不知道源數據數組的尺寸,那么我們需要一個可以增長的動態容器,例如std::vector

在所有情況下,我們都可以將索引運算符 [] 與標准 for 循環或基於范圍的帶有引用的 for 循環一起使用。 沒有區別。


例子:

具有標准 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 樣式數組 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與基於范圍的 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";
}

動態解決方案,帶有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";
}

基本上,一切都是一樣的。 . .

還有很多其他方法可以執行特定任務,但我想你的方法沒有錯,而且你剛剛在第二個 for 循環條件中犯了一個簡單的輸入錯誤。 所以我只是為你修復你的代碼。 你也可以一次只輸入一個值作為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: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM