How to read from a .txt file

I wrote a matrix (table) and 2 other variable values in a text file.

1
2
3
matrix table={ {0.5, 0, 0, 0, 0.7}, {1, 2, 3, 4, 0}, {2, 3, 4, 0, 1}, {3, 4, 0, 1, 2}, {4, 0, 1, 2, 3}, {0, 1, 2, 3, 4}};
   double a = 0.1; 
   int b = 1;


table.txt content

0.5	0	0	0	0.7	
1	2	3	4	0	
2	3	4	0	1	
3	4	0	1	2	
4	0	1	2	3	
0	1	2	3	4	
0.1
1



Now I need to read the matrix and the other 2 variable values.

To read the matrix, I am using the below code.

Would anyone suggest me what to add to the below code to read the other two variable values (0.1 and 1)? Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  istream &operator >> ( istream &in, matrix &M )
{
   M.clear();                                          
   for ( string line; getline( in, line ); )          
   {
      stringstream ss( line );                        
      vector<double> row;
      for ( double e; ss >> e; row.push_back( e ) );   
      M.push_back( row );                              
   }
   return in;
}


int main()
{
   matrix table;
   ifstream inFile( "table.txt" );
   inFile >> table;
   // How to read the 2 variable values
}
Last edited on
@telco,
If there is more than just the matrix in the input file then you won't be able to use an overloaded >> operator like that, because it won't know how many rows there are in the matrix.

You have to either specify the matrix size in advance, or give the number of rows (at least) to the procedure that will read the matrix. The following example gives both number of rows and number of columns.

I think it would be better if:
(a) you stated all your requirements up front;
(b) you did some background reading to actually learn about input and output;
(c) you continued the same thread, rather than starting a succession of different ones.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
using matrix = vector< vector<double> >;

//======================================================================

ostream &operator << ( ostream &out, const matrix &M )
{
   for ( auto &row : M )
   {
      for ( auto e : row ) out << e << '\t';
      out << '\n';
   }
   return out;
}

//======================================================================

matrix readMatrix( istream &in, int rows, int cols )
{
   matrix M( rows, vector<double>( cols ) );
   for ( int i = 0; i < rows; i++ )
   {
      for ( int j = 0; j < cols; j++ ) in >> M[i][j];
   }
   return M;
}

//======================================================================

int main()
{
   const int ROWS = 6, COLS = 5;
   double something, something_else;

   ifstream inFile( "table.txt" );
   matrix table = readMatrix( inFile, ROWS, COLS );
   inFile >> something >> something_else;

   cout << table;
   cout << something << '\n';
   cout << something_else << '\n';
}


0.5	0	0	0	0.7	
1	2	3	4	0	
2	3	4	0	1	
3	4	0	1	2	
4	0	1	2	3	
0	1	2	3	4	
0.1
1
Last edited on
@lastchance, Thank you. I understand what you meant. During my last post, i did not know i would need to save more variable in the text file and read it. Thanks for answers.

Last edited on
I have been reading a book titled "C++ in One Hour a Day". Following the book, I wrote the following code to read a text file. In the text file, i typed in a matrix and two other variable values before coding.

txt file content

0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0
0	0	0	0	0	0	0	0	0	0
0	0	0	0	0	0	0	0	0	0
0	0	0	0	0	0	0	0	0	0
0	0	0	0	0	0	0	0	0	0	
0.1
1


IThis time I have to use valarray. The below code has no compilation error but when i execute it shows
Segmentation fault (core dumped)

Does anyone have any suggestions? Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <valarray>
#include <cstdlib>
#include <iomanip>

using namespace std;

using matrix = valarray< valarray<double> >;


int main()
{

//read 
  
  matrix table;
  double a;
  int b;


  fstream inFile;
  inFile.open("tablenew1.txt", fstream::in);
if (inFile.is_open())
{

  for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            inFile >> table[i][j];
           
        }
        
       
    }
inFile >> a; 
inFile >> b;
inFile.close();
}

//printout 
   
   for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            std::cout << std::fixed;
            std::cout << std::setprecision(4);
            cout << table[i][j] << "\t";
        }
        cout << endl;
    }

   cout << a << '\n';
   cout << b << '\n';
return 0;

}
You haven't specified the size of your array. So it is zero. So you can't read 100 items into it.

If you are going to use valarrays then you might like to "flatten" it to 1-d, or you will incur the wrath of the Gods!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <valarray>
#include <iomanip>
using namespace std;

int main()
{
   const int ROWS = 10, COLS = 10;
   valarray<double> table(ROWS*COLS);       // "flattened" to 1d
   double a;
   int b;
   
   ifstream inFile( "tablenew1.txt" );
   for ( int n = 0; n < ROWS * COLS; n++ ) inFile >> table[n];
   inFile >> a >> b;

   cout << fixed << setprecision( 4 );
   for (int n = 0; n < ROWS * COLS; n++ )
   {
      cout << table[n] << '\t';
      if ( (n+1)%COLS == 0 ) cout << '\n';      
   }
   cout << a << '\n';
   cout << b << '\n';
}



It's easier in Fortran or python, where there is proper array slicing and easier multi-dimensional arrays.
program telco
   implicit none
   integer, parameter :: ROWS = 10, COLS = 10
   real a, table(ROWS,COLS)
   integer b, i

   open( 10, file="tablenew1.txt" )
   read( 10, * ) ( table(i,:), i = 1, ROWS ), a, b
   close( 10 )
   
   do i = 1, ROWS
      write( *, "( *(f6.3,1x) )" ) table(i,:)
   end do
   write( *, "(f6.3,/,i0)" ) a, b
end program telco
Last edited on
Topic archived. No new replies allowed.