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' ;
}
|