如何从文本文件中读入数组 C++

How to read into an array from a text file c++

如果这个问题看起来有点愚蠢,我很抱歉,但即使我已经尝试了很多次,我还是无法让它工作。所以我的问题是,我有一个文本文件,里面有一个数字,如下所示:

10 20 30
30 40 50
60 70 80

数字、行大小和列大小是用户输入的。到目前为止,我已经为所有这些编写了代码。这意味着用户可以输入行大小、列大小和整数。但我无法从这个文件中读入一个数组。我能为此做什么?

请注意,在 C++ 中,内置数组的大小 必须是 一个 编译时常量 。因此,您不能将行和列作为用户的输入,然后将这些变量用作内置数组的大小。

更好 的替代方法是使用 2D vector,如下所示。在数组上使用 vector 优点 是您 不需要 预先指定(知道)行和列.也就是说,文本输入文件可以有任意多的行和列,并且不需要询问用户文件有多少行和列。 std::vector 照料 它,如下所示。

下面的程序使用 2D std::vector 以二维方式存储信息(如本例中的整数值)。从文件中读取所有值后,您可以根据需要处理向量。显示的程序从 input.txt 读取数据(int 值)并将这些数据存储在二维 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;
}

上面程序的输出可见here。上面提到的 link.

也给出了读取 int 值的输入文件

使用矢量的优势

  1. 您不需要向用户询问输入文件中的行数和列数。

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

  3. std::vector 负责为您管理内存。所以你不必自己使用 newdelete 需要更多 attention/care.

2d矢量解决方案非常好。但是如果你不想使用向量,你也可以使用二维动态数组。 如果您特别想输入行和列并从文件中读取,这也是一个可以使用二维动态数组的解决方案。这对您来说是一个有点高级的概念,因为它包含在 C++ OOP 中,但您可以根据您的要求轻松地将 .txt 文件读入二维数组。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void main()
{
    int rows=0,cols=0;
    cout<<"Enter your rows: ";
    cin>>rows;
    cout<<"Enter your rows: ";
    cin>>cols;

    int** arr= new int*[rows];
    for(int k=0;k< rows; k++)
        arr[k]= new int[cols];

    ifstream read_num;
    read_num.open("matrix.txt");
    if(read_num.is_open())
    {
        for(int x=0;x<rows; x++)
        {
            for(int y=0;y<cols; y++)
            {
                read_num>>arr[x][y];
            }
        }
    }
    else
        cout<<"Failed to open file"<<endl;

    cout<<"After reading data from file:"<<endl;
    for(int x=0; x<rows; x++)
        {
            for(int y=0; y< cols; y++)
            {
               cout<<arr[x][y]<<" ";
            }
            cout<<endl;
        }
     read_num.close();

     for (int i = 0; i < rows; i++)
     {
        delete [] arr[i];
     }
 delete[] arr;

    system("pause");
}

可以看到这段代码的输出结果here,代码中的输入文件命名为matrix.txt.