【问题标题】:How to read into an array from a text file c++如何从文本文件c ++读入数组
【发布时间】:2022-01-10 23:44:42
【问题描述】:

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

10 20 30
30 40 50
60 70 80

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

【问题讨论】:

  • 你试过什么?请包含源代码的相关部分。
  • 为什么不能从文件中读取?你有什么问题?
  • @ChrisMM 所以 c++ 不允许我创建一个大小为输入的数组并从文本文件中读取到数组中。据我所知
  • 啊,你的意思是可变长度数组,不,它们不是 C++ 的一部分。您可以改用矢量。
  • 查找时间:从文本文件中读取 (std:) 字符串。以及如何将这样的字符串转换为数字。检查循环可能也是个好主意

标签: c++ arrays file-handling


【解决方案1】:

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

更好的替代方法是使用 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;
}

上面程序的输出可以看到here。上面提到的链接也给出了读取 int 值的输入文件。

使用矢量的优势

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

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

  3. std::vector 为您处理内存管理。所以你不必自己使用newdelete,这需要更多的关注/照顾。

【讨论】:

    【解决方案2】:

    二维向量解相当不错。但是,如果您不想使用向量,也可以使用 2d 动态数组。 如果您特别想输入行和列并从文件中读取,这也是一个解决方案,您可以在其中使用 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。

    【讨论】:

    • 您的程序有 3 个缺点。 1) 需要事先指定行和列。 2) 它不能处理文本文件一行中不均匀的条目。 3) 它需要显式释放new 分配的内存。所以它需要手动管理内存,应该尽量避免。
    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    相关资源
    最近更新 更多