How to read from a file and store two specific columns in a 2d array

closed account (EAk1vCM9)
Hey guys its me again. so im trying to store a file into a 2-dimensional int array with 500 rows and two columns. However I need to store the first column of file (the Date) and the fifth column of file (the Close) into the two columns of my array. Ive tried doing this and made a cout to see what was being stored into the array and i found out that it just took in the first date and then printed 0 and garbage values. I noticed that the close data was a float and though that was the thing causing issues but when i tried to convert it, it didnt work I just ended in a infinite loop. I reread the requirements and saw a note that said: "Note, the floating point Close value should be converted to a rounded int value." so I guess I was in the right track, problem Is though I dont know how to only read in and store the first columns and the fifth columns and my conversion doesnt really work. any help on how do this would be very appreciated . ps. I also moved everything from main to a different function and I had a question, since I would want to return the data stored in the 2d array back to main would I need a return something or since the array is pass by reference I wouldnt need a return ??
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    #include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

const int numRows=500;
const int cols=2; // not sure if I need to make this a constant ....


int modifyAndgetDataFromFile(int data[][2]);
int main() {



return 0;
}
int modifyAndgetDataFromFile(int data[][2])
{


ifstream infile, infile2;
ofstream modifiedFile;
string dummy;
float tempFloat;
char ch ;
// int data[numRows][cols];

infile.open("vtsmx.csv");
modifiedFile.open("vtsmxModified.csv");

if(!infile)
{
cout << "Error opening the file" << endl;
return 1;
}
else
{
getline(infile,dummy);

while ( infile.get( ch ) )        // Use the ability to read the stream instead
       {
          if (ch != '-' )                // If it's not a hyphen then you will write something ...
          {
             if ( ch == ',' ) ch = ' ';  // ... but you may need to change it first

             modifiedFile.put( ch );
          }
       }

infile.close();
modifiedFile.close();
}
infile2.open("vtsmxModified.csv");
if(!infile2)
{
cout << "error opening file";
}
else
{
while(!infile2.eof()) // just trying to see if this helped
{
for(int i=0; i< numRows; i++)
{
data[i][5]= static_cast<int>(tempFloat * 100); //attempt to convert float to rounded int
}
/* for(int i = 0; i < numRows; i++) // attempt to read file into 2d array
{
     for(int j = 0; j < cols; j++)
     {
         infile2 >> data[i][j];
     }
}



for(int i = 0; i < numRows; i++) // me checking to see what it read
{
for(int j = 0; j < cols; j++)
{
cout << data[i][j] <<" " ;
}
cout <<endl;
}



}*/

}
}


// im trying to return the array to main not sure if I need to return(something);
}


This is how the array should look like

20151016 5086
20151019 5088
20151020 5081
20151021 5044
20151022 5120
20151023 5172
20151026 5161
20151027 5142
20151028 5213
20151029 5205

Heres a couple lines from the file
20151016 50.860001 50.860001 50.860001 50.860001 49.009617 0
20151019 50.880001 50.880001 50.880001 50.880001 49.028889 0
20151020 50.810001 50.810001 50.810001 50.810001 48.961437 0
20151021 50.439999 50.439999 50.439999 50.439999 48.604893 0
20151022 51.200001 51.200001 51.200001 51.200001 49.337242 0
20151023 51.720001 51.720001 51.720001 51.720001 49.838326 0
20151026 51.610001 51.610001 51.610001 51.610001 49.732330 0
20151027 51.419998 51.419998 51.419998 51.419998 49.549244 0
20151028 52.130001 52.130001 52.130001 52.130001 50.233410 0
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <fstream>
#include <string>
#include <cmath> // for std::round

const int num_rows = 500 ;
const int num_cols = 2 ;

bool create_modified_file( std::string in_file_name, std::string modified_file_name )
{
    std::ifstream infile(in_file_name);
    if( !infile.is_open() ) { /* error opening input file */ return false ; }

    std::ofstream modifiedFile(modified_file_name);

    std::string line ;
    std::getline( infile, line ) ; // discard the first line

    char c ;
    while( infile.get(c) ) // for each character in the input file
    {
        if( c == '-' ) ; // do nothing: ignore '-'
        else if( c == ',' ) modifiedFile << ' ' ; // substitute space for comma
        else modifiedFile << c ; // copy other characters as they are
    }

    // return true if we read everything from the input file
    //                and wrote to the output file without errors
    return infile.eof() && modifiedFile.good() ;
}

// return number of rows read, up to a maximum of num_rows
int read_modified_file( int array[num_rows][num_cols], std::string modified_file_name )
{
    std::ifstream file(modified_file_name); // open modified file for input

    int date ; // integer value (first col)
    std::string col2, col3, col4 ; // second, third, fourth columns
    double close ; // floating point value (fifth col)
    std::string tail ; // everything after the fifth col

    int cnt = 0 ; // count of data sets read
    // read an entire line into date, col2, col3, col4, close and tail
    while( cnt < num_rows && file >> date >> col2 >> col3 >> col4 >> close && std::getline( file, tail ) ) // for each line read
    {
        array[cnt][0] = date ; // place the date as it is into column zero

        // the floating point Close value should be converted to a rounded int value.
        // http://en.cppreference.com/w/cpp/numeric/math/round
        array[cnt][1] = std::lround(close) ; // and placed into column one of the array

        ++cnt ;
    }

    return cnt ;
}

// return number of rows read, up to a maximum of num_rows
int modify_and_get_data_from_file( int data[num_rows][num_cols],
                                   std::string in_file_name, std::string modified_file_name )
{
    if( create_modified_file( in_file_name, modified_file_name ) )
        return read_modified_file( data, modified_file_name ) ;

    else return 0 ; // error in creating modified file
}

int main()
{
    int data[num_rows][num_cols] ;

    const int nrecs = modify_and_get_data_from_file( data, "vtsmx.csv", "vtsmxModified.csv" ) ;

    // verify that things are ok by printing out nrecs rows
    for( int i = 0 ; i < nrecs ; ++i ) std::cout << data[i][0] << ' ' << data[i][1] << '\n' ;
}
Last edited on
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;

using vec = vector<string>;
using matrix = vector<vec>;

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

matrix readCSV( string filename )
{
   char separator = ',';
   matrix result;
   string row, item;

   ifstream in( filename );
   while( getline( in, row ) )
   {
      vec R;
      stringstream ss( row );
      while ( getline ( ss, item, separator ) ) R.push_back( item );
      result.push_back( R );
   }
   in.close();
   return result;
}

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

void deleteRow( matrix &M, int row )
{
   if ( row < M.size() ) M.erase( M.begin() + row );
}

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

void deleteCol( matrix &M, int col  )
{
   for ( vec &row : M )
   {
      if ( col < row.size() ) row.erase( row.begin() + col );
   }
}

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

string removeChars( string s, string getRidOf )
{
   string result;
   for ( char c : s ) if ( getRidOf.find( c ) == string::npos ) result += c;
   return result;
}

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

int modCol( string s )
{
   double d = stod( s );
   return (int)( 100 * d + 0.5 );
}

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

int main()
{
   matrix MAT = readCSV( "vtsmx.csv" );                    // Read whole CSV file
   deleteRow( MAT, 0 );                                    // Delete header row

   int col = 1;                                            // Chosen column
   ofstream out( "vtsmxModified.csv" );
   for ( int i = 0; i < MAT.size(); i++ ) out << removeChars( MAT[i][0], "-" ) << " " << modCol( MAT[i][col] ) << '\n';
}

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

closed account (EAk1vCM9)
Thanks for the help guys I ended up modifying a bit of JLBorges read_modified_file function and ended up getting what I need . Again thank you.
Topic archived. No new replies allowed.