Home > Blockchain >  How to read into an array from a text file c
How to read into an array from a text file c

Time:12-06

I am sorry if this question seems a bit dumb but i can't get it working even though i have tried many times. So my question is, i have a text file which has a numbers inside it like the following:

10 20 30
30 40 50
60 70 80

The numbers, the row size and the column size are inputs from the user. So far i have written the code for all of this. Which means that user can enter row size, column size and the integers. But i can't read from this file into an array. What can i do for this?

CodePudding user response:

Note that in C , the size of a built in array must be a compile-time constant. So you can't take the rows and columns as input from the user and then use those variables as size of a built in array.

A better alternative would be to use a 2D vector as shown below. The advantage of using a vector over an array is that you don't need to specify(know) the rows and columns beforehand. That is, the text input file can have as many rows and columns and there is no need to ask the user how many rows and columns does the file have. std::vector will take care of it as shown below.

The below program uses a 2D std::vector for storing information(like integers values in this case) in 2D manner. 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. 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. The input file through which int values are read is also given at the above mentioned link.

Advantage of using vector

  1. You don't need to ask the user for the number of rows and columns in the input file.

  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. So you don't have to use new and delete by yourself which needs more attention/care.

CodePudding user response:

The 2d vector solution is quite good. But if you don't want to use vectors you can use 2d dynamic arrays as well. Here is also a solution where you can use 2d dynamic arrays if you specifically want to input the rows and cols and read from the file. It would be a bit advanced concept for you as it is covered in C OOP but you can easily read from your .txt file into a 2d array just according to your requirement.

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

The output of this code can be seen here and the input file in the code is named as matrix.txt.

  • Related