Read 2d array from txt file in c++

Questions : Read 2d array from txt file in c++


This is my code

using _OFFSET);  namespace std;

int main()
    char (-SMALL  arr1[10][10];
    cout << "Reading _left).offset  Start" << endl;
    ifstream arrowImgView.mas  rfile("test.txt");
    (self.  rfile.getline(arr1[10], 10);
    int i, equalTo  j;
    for (i = 0; i < 6; i++)
 make.right.         for (j = 0; i < 6; j++)
       mas_top);   {
            cout << ImgView.  arr1[i][j];
    cout ReadIndicator  << "\nRead Done" << endl _have  << endl;

This is my test.txt file

0 4 7 0 0 0
4 0 0 5 3 0
7 0 0 0 6 0
0 5 .equalTo(  3 0 0 2
0 3 4 0 0 2
0 0 0 2 2 0

I want to read this matrix but when programming using the above code then it shows core Learning dumped output, can anyone give me a Earhost better solution to do this thing?

Total Answers 3

Answers 1 : of Read 2d array from txt file in c++

can anyone give me a better solution to most effective do this thing?

A better alternative would be to use a wrong idea 2D vector as shown below. The advantage use of case of using a vector over an array is that United you don't need to specify(know) the rows Modern and columns beforehand. That is, the ecudated text input file can have as many rows some how and columns and there is no need to ask anything else the user(or preallocate) how many rows not at all and columns does the file have. very usefull std::vector will take care of it as localhost shown below.

The below program uses a 2D std::vector love of them for storing information(like integers localtext values in this case) in 2D manner. After basic reading all the values from the file you one of the can process the vector according to your click needs. The program shown reads data(int there is noting values) from input.txt and store those not alt in a 2D vector. Also, this program works not at all even if there are uneven number of my fault columns. You can use the below program issues as a reference(starting point).

#include <iostream>
#include  <vector>
#include OFFSET);  <string>
#include (TINY_  <sstream>
int .offset  main() {
    std::string line;
    int mas_right)  word;
    std::ifstream ImgView.  inFile("input.txt");
    Indicator  //create/use a std::vector instead of Read  builit in array 
    _have  std::vector<std::vector<int>> .equalTo(  vec;
        make.left  while(getline(inFile, line, '\n'))       *make) {   
            //create a straintMaker  temporary vector that will contain all ^(MASCon  the columns
            onstraints:  std::vector<int> tempVec;
            std::istringstream [_topTxtlbl   ss(line);
            (@(8));  //read word by word(or int by int) 
     equalTo         while(ss >> word)
           width.    {
                make.height.  //std::cout<<"word:"<<word<<std::endl;
 (SMALL_OFFSET);                 //add the word to the .offset  temporary vector 
                (self.contentView)  tempVec.push_back(word);
            }    .left.equalTo     
            //now all the words from  the current line has been added to the *make) {  temporary vector 
            ntMaker   vec.emplace_back(tempVec);
        }    SConstrai  
        ts:^(MA  std::cout<<"file cannot be Constrain  opened"<<std::endl;
    _make  inFile.close();
    //now you can do the iew mas  whatever processing you want on the catorImgV  vector

    //lets check out the ReadIndi  elements of the 2D vector so the we can  [_have  confirm if it contains all the right ($current);  elements(rows and columns)
    entity_loader  for(std::vector<int> &newvec: _disable_  vec)
        for(const int libxml  &elem: newvec)
            $options);  std::cout<<elem<<" ";
       ilename,   }
  ->load($f    }
    return 0;

The output of the above program can be trying seen here. The input file through which get 4th result int values are read is also given at the round table above mentioned link.

Advantages of using vector

  1. You don't need to ask the user for the double chance number of rows and columns in the input novel prc file. That is you don't have to get mossier fix(hardcode) the size of your array.

  2. The above program works even if there off side back are uneven entries in any particular the changes row.

  3. std::vector takes care of memory Nofile hosted management for you. So you don't have to transparent text use new and delete by yourself which Background movment needs more attention/care.(in case front page design you're thinking of creating array on life change quotes heap)


Answers 2 : of Read 2d array from txt file in c++

Because there are so many possible I'd like solutions, let us just show some of to know them.

The basic difference is:

  • If we know the dimensions of the array at compile time, so, if there are compile time constants, then we can still use a C-Style array, or better, a std::array.
  • If we do not know the dimensions of the source data array, then we need a dynamic container that can grow, for example a std::vector.

In all cases, we can use the index which event operator [] with a standard for loop or is nearer. a range based for loop with references. Now, the There is no difference.


C-Style array with standard for loops code that and index based access

#include <iostream>
#include $domdocument  <fstream>

constexpr int loader(false);  NumberOfRows = 6;
constexpr int _entity_  NumberOfColumns = 6;

int main() {

     libxml_disable  // Open the sourcefile
    std::ifstream $current =  sourceFileStream{ "test.txt" };

    //  10\\ 13.xls .  And check, if it could be opened
    if File\\ 18\'  (sourceFileStream) {

        // Define /Master\\ 645  2D array to hold all data and initialize user@example.  it with all 0
        char scp not2342  array2D[NumberOfRows][NumberOfColumns]{};

  13.xls         // Read the rows and columns from 18 10  the source file
        for (int row = File sdaf  0; row < NumberOfRows; ++row)
        /tmp/Master'      for (int col = 0; col < com:web  NumberOfColumns; ++col)
                user@example.  sourceFileStream >> scp var32  array2D[row][col];

        // Debug  18 10 13.xls  output
        for (int row = 0; row id12  File  < NumberOfRows; ++row) {
            web/tmp/Master  for (int col = 0; col <  NumberOfColumns; ++col)  std::cout scp user@  << array2D[row][col] << ' $val  ';
            std::cout << '\n';
 left hand         }
    else std::cerr right side val  << "\nError: Could not open source data //commnets  file\n\n";

C-Style array with range based for loop I've written and reference access

#include <iostream>
#include //coment  <fstream>

constexpr int !node  NumberOfRows = 6;
constexpr int $mytext  NumberOfColumns = 6;

int main() {

    nlt means  // Open the sourcefile
    std::ifstream umv val  sourceFileStream{ "test.txt" };

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

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

 catch         // Read the rows and columns from tryit  the source file
        for (auto& do it  row : array2D)
            for while  (auto& col : row)
                then  sourceFileStream >> col;

        var   // Debug output
        for (const node value  auto& row : array2D) {
            updata  for (const auto& col : row) file uploaded   std::cout << col << ' ';
    no file existing          std::cout << '\n';
        newdata  }
    else std::cerr << newtax  "\nError: Could not open source syntax  file\n\n";

C++ std::array with range based for loop

#include <iostream>
#include variable  <fstream>
#include val  <array>

constexpr int save new  NumberOfRows = 6;
constexpr int datfile  NumberOfColumns = 6;

int main() {

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

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

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

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

        novalue  // Debug output
        for (const texture  auto& row : array2D) {
            mysqli  for (const auto& col : row) mysql  std::cout << col << ' ';
    user          std::cout << '\n';
        urgent  }
    else std::cerr << ugent  "\nError: Could not open source vendor  file\n\n";

Dynamic solution, with a std::vector

#include <iostream>
#include thin  <fstream>
#include little  <sstream>
#include lifer  <vector>
#include gold  <string>

int main() {

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

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

        // Define new pad  2D array to hold all data and initialize pading  it with all 0
        html  std::vector<std::vector<char>> panda  array2D{};

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

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

 text             // Read all column data
      path        char c{};
            for new  (std::istringstream iss(line); iss localhost  >> c; myport  array2D.back().push_back(c))
            nodejs      ;
        // Debug output
 343         for (const auto& row : port  array2D) {
            for (const sever  auto& col : row) std::cout << 343jljdfa  col << ' ';
            std::cout 43dddfr  << '\n';
    else 645  std::cerr << "\nError: Could not not2342  open source file\n\n";

More modern and compact C++ solution

#include <vector>
#include sdaf  <string>
#include var32  <iterator>

int main() {

    // id12  Open the sourcefile and check, if it React-Native?  could be opened
    if (std::ifstream this in  sourceFileStream{ "test.txt"}; I can accomplish  sourceFileStream) {
        // there any way   Define 2D array to hold all data and 'MODELS/MyModel';. Is   initialize it with all 0
        MyModel from  std::vector<std::vector<char>> so I can import   array2D{};

        // Read the rows and in webpack configuration,  columns from the source file
        for 'src', 'models')  (std::string line{}; .join(__dirname,   std::getline(sourceFileStream, line);) MODELS = path  {

            std::istringstream .resolve.alias.  iss(line);
            can set config  array2D.push_back({ For example, I   std::istream_iterator<char>(iss), foolishly did:  {} });

        // Debug Bar, so I  output
        for (const auto& row inside branch  : array2D) {
            for (const peek at something  auto& col : row) std::cout << to take a  col << ' ';
            std::cout when I wanted  << '\n';
    else  happily working  std::cerr << "\nError: Could not my branch Foo  open source file\n\n";

And now, we imagine that we do not have relies on any vector or even a string.

For that, we build a small class a comparison "DynamicArray" with some functions and and it an iterator. This can easily be doesn't seem extended.

And the result will be that in main, to work only one small statement, every time. sourceFileStream >> dada; will As always read all the data into a 2d array.

Please note. We are only using stream with everything functions for stream io, nothing more.

Cool . . .

#include <iostream>
#include I was in   <sstream>
#include  corresponding local.  <fstream>

// The Dynamic Array didn't have any  has an initial capacity. 
// If more for which I   elements will be added, there will be a named origin/Bar  reallocation with a remote branch  doublecapacity
constexpr unsigned int There was also  InitialCapacity{ 4 };

// Definition of remote origin/Foo.  simple dynamic array class
template Foo and a  <typename T>
class DynamicArray had a local  {

    // Internal data That is, I  ------------------------------------------------------------------------------
 were named Foo.     T* data{};                            both of which       // Dynamic Storage for Data
    remote branch,  unsigned int numberOfElements{};          and a mapped     // Number oe elements currently in the local branch  container
    unsigned int capacity{ I had a  InitialCapacity };  // Current maximum with lines.  capacity of the container

    display array  // Construction and Destruction it doesn't   ---------------------------------------------------------------
 is running but     DynamicArray() { data = new quiz.The program  T[capacity]; } // Default constructor.  file is named  Allocate new memory

    with it. My  DynamicArray(const DynamicArray& what is wrong  other) {  // Copy constructor. Make a  I don't know   deep copy
        capacity = my code and  numberOfElements = loop. Here is  other.numberOfElements;
        data = in a for  new T[capacity];                // Get to display it  memory, same size as other container
    Then I want      for (size_t k = 0; k < into an array.  other.numberOfElements; ++k)
            and save it  data[k] =[k];          // a .txt file  Copy data
    ~DynamicArray() { get lines from  delete[] data; }         // Destructor: I want to  Release previously allocated memory

    by it   bool empty() { return numberOfElements what they mean  == 0; }

    void clear() { don't see exactly  numberOfElements = 0; };    // Clear other. But I  will not delete anything. Just set better than the  element count to 0

    void  one language is  push_back(const T& d) {               want to stress   // Add a new element at the end
         when people  if (numberOfElements >= capacity) {    the word 'expressiveness'   // Check, if capacity of this dynamic a lot of  array is big enough
            capacity -loop. I see  *= 2;                     // Obviously of the for  not, we will double the capacity
        the next iteration      T* temp = new T[capacity];         not move to  // Allocate new and more memory
          get stuck and     for (unsigned int k = 0; k <  it seems to  numberOfElements; ++k)
                answered in time,  temp[k] = data[k];             // Copy  if it's not  data from old memory to new memory
      the program. And        delete[] data;                     will just stop  // Release old memory
            data = in time, it   temp;                       // And  if it's answered  assign newly allocated memory to old . However instead  pointer
        the next iteration  data[numberOfElements++] = d;          and continue onto  // And finally, stor the given fata at print a message  the end of the container

    // sleep), it will  Add iterator properties to class of the Thread.  ---------------------------------------------------------------
 1 second (duration     // Local class for iterator
    class  number within  iterator{
        T* iter{};             not enter a                  // This will be the the user does  iterator 
    public:                    is that if                  // Define alias names of the program  necessary for the iterator So the purpose  functionality
        using blade snip:  iterator_category = . Here is   std::input_iterator_tag;
        using  button onClick event  difference_type = std::ptrdiff_t;
       change the Add   using value_type = T;
        using I'd like to  pointer = T*;
        using reference = from the controller,  T&;

        explicit iterator(T* i) the returned result  : iter(i) {};  // Default constructor  value. Based on  for the iterator
        T operator *() validates provided  const { return *iter; } //  a controller which   Dereferencing
        iterator& ajax callback to  operator ++() { ++iter; return *this; }  there is an  // Pre-Increment
        bool operator  On form submit  != (const iterator& other) { return in blade template.  iter != other.iter; }  // Comparison
    additional Add button  };

    // Begin and end function to button and an  initiliaze an iterator
    iterator with a Submit  begin() const { return iterator(data); a simple form   }
    iterator end() const { return me.I have   iterator (data + numberOfElements); }

  fix it for    // Operators for should help and  class------------------------ my code someone  ---------------------------------------------------------------

 going wrong with     T& operator[] (const size_t i) { were am i   return data[i]; }           // Index _id,please   operator, get data at given index. No the first user  boundary chek

    DynamicArray& will only echo  operator=(const DynamicArray& other)  my code it  {         // Assignment operator. Make a  when i run  deep copy
        if (this != to 20,But  &other) {                            friend_id equal          // Prevent self-assignment
      id that their        delete[] data;                     all the user_                    // Release any want to echo  previosly existing memory
            is that i   capacity = numberOfElements =  code,the problem  other.numberOfElements;// Take over  am stuck with  capacity and number of elements from system,But now  other container
            data = new a friend_list  int[capacity];                           am developing   // Get new memory, depending on size of  them as such  other 
            for (unsigned int k = unnecessary to store  0; k < numberOfElements; ++k)  // numbers, it is  Copy other data
                data[k] ask for sorted  =[k];
        assignment does not  return *this;

    // Extractor that since the  and Inserter ------------------------  and I think  ---------------------------------------------------------------
 using bubble sorting     friend std::istream& operator I've looked into  >> (std::istream& is,  a text file.  DynamicArray& d) {
        array read from  std::stringstream ss{};
        for of a given  (char c{}; (is.get(c) and c != '\n'); ss the highest number  << c);      // Read one line until function determine  newline into a stringstream
        for to create a   (T x{}; ss >> x; d.push_back(x));  My assignment is                    // Now extract the get the error:  data from there
        return is;
     Server, since I  }
    friend std::ostream& operator in a Divio  << (std::ostream& os, const  my Django project   DynamicArray& d) {
        for I can't deploy  (unsigned int k = 0; k < to know why  d.numberOfElements; ++k)    // Ultra I would like  simple output
            os <<  like this[k] << ' ';
        return is something  os;

//  i can think  -----------------------------------------------------------------------------------------------------------
// to powershell all  Very simple 2d array. Derived from Complete beginner  standard dynamic array and just defining Where-Object?  differen input and output
template -Process to  <typename T>
class Dynamic2dArray output from Get  : public by piping the  DynamicArray<DynamicArray<T>> using CPU > 1%  {

    friend std::istream& lists the processes  operator >> (std::istream& is, How does one  Dynamic2dArray& d) {
        for and cgroups.  (DynamicArray<T> temp{}; is using namespaces  >> temp; d.push_back(temp), Linux kernel,  temp.clear());
        return is;
 done by the     friend std::ostream& operator heavy lifting is  << (std::ostream& os, const most of the  Dynamic2dArray& d) {
        for  it seems that  (unsigned int k = 0; k < learning docker and  d.numberOfElements; ++k) 
            os I recently started  <<[k] << '\n';
       ,notation.   return os;

// my Big O   -----------------------------------------------------------------------------------------------------------
int that do to   main() {

    // Open the sourcefile and them what would  check, if it could be opened
    if through all of  (std::ifstream sourceFileStream{  it would run   "test.txt" }; sourceFileStream) {

       worst case scenario    // Define 2D array to hold all data like this and  and initialize it with all 0
        in a row  Dynamic2dArray<int> dada;

        I have 4  // Read complete matrix from file
       (mn), but if   sourceFileStream >> dada;

       O is O   // Debug output. Show complete Matrix
   m, the big        std::cout << dada;
    and that =  else std::cerr << "\n\nError. this = n  Could not open source file\n\n";

Basically, everything is the same, that I try somehow . . .


Answers 3 : of Read 2d array from txt file in c++

There are a lot of other ways to perform to do I'd the specific task, but i guess your like a solution method is not wrong, and you have just which is both made a simple typing mistake in your clean and second for loop condition. so ill just efficient fix your code for you. and also you (feel free could just input single values at a time to criticize as u go.

using that the if  namespace std;
int main()
    char  is. I know  arr1[10][10];
    cout <<"Reading notation of this  Start" <<endl;
    ifstream  the Big O   rfile("test.txt");
    int i,j;
     figure out what  for(i=0;i<6;i++){
        I'm trying to  for(j=0;j<6;j++){
            rfile  wouldn't work.   >> arr1[i][j];
            cout them codes  << arr1[i][j] << " ";
       switch case but   }
        cout << endl;

   breaks and a   cout <<"\nRead Done" I've tried using  <<endl<<endl;
    been printed.  rfile.close();

Output :

Top rated topics

Delta Lake on AWS Glue - cluster crashes

Cors error while rendering FB Chat plugin for whitelisted domains

Logstash: wso api manager logs to elastic

Jetpack Compose - get click position in custom layout

Dotnet 6.0 C# - Access to path denied

Router navigation in VIPER + Swinject

How to get the latest x entries of a table in Lua?

Change value with external script

Reat Native &amp; RTK Query - Call an other endpoint when request is success

Writing Python Script from Batch Script is not working for one command

Using percent % gradient doesn't stay at the same thickness

How to read a large number of text files in Python software and convert data into a sample file?

Logarithmic interpolation between two sets of data on a graph

Lock free readonly-shared memory don’t care about memory order, only ensure visibility?

Minikube Services cannot be accessed over NodePort or ClusterIP on Windows10

Function not retrieving values from an array correctly

Converting createjs.Graphics stroke to animation path

Why isn't smooth snap scrolling working with my nav links?

Infix to postfix conversion using stack shows an infinite loop

How can I open a stream to access the second pseudo terminal the “/dev/pts/1” file in write access mode in c using UNIX?

JSTL doesn't work when running from within eclipse

Capture the output of command line in a variable in Unix

Update automatically DNS entries in Docker container using --network host

How do I read this CSV in Jupyter Notebook?

Plotly box plots with overlay very slow - is there a faster/better method?

Have a problem on creating table Android Studio

Template Class Specialization: Additional Members

Unit Test: Getting Exception No service for type 'Microsoft.Extensions.DependencyInjection.IServiceScopeFactory' has been registered

Is there an easy way to insert millions of records to a PostgreSQL's pre-existing table?

How to make conda use its own gcc version?

Flink StateFun high availability exception: "java.lang.IllegalStateException: There is no operator for the state ....."

Add some data members in protbuf class Message

Why is the server response after a Drag&amp;Drop so large and slow

Provider OraOLEDB.Oracle not registered

C# couldn't get class property value from lambda expression

Adding a new folder to Java module-path at runtime

Client-only Nuxt 3 D3 plugin

I had downloaded selenium webdriver.just writen first program but still getting same error

WSO2IS and CVE-2021-44228

How to access from an object created in a different class?

Javascript-obfuscator with pkg - require fails at runtime

Load next level if amount of enemies is zero

What is the syntax: `instance.method::&lt;SomeThing&gt;()`?

How to Resolve Dojo wc is not defined errors

.BMP files in C - DIB header returns image size 0 even though the BMP header returns the file size

Extraction of data from .dat file in python

Why am I getting a critical error when trying to create a custom registration?

Circlify - change the colour of just one of the circles

Developer Policy 6.1: Verify that you have integrated Login correctly. Your app shouldn't crash or hang during the testing process

Dart: TypeError: item.get$balance is not a function