A file is neither "string" or "double". It is just a series of bytes.
Since this is a .CSV file, we know it is series of ASCII bytes and does not contain binary values. How you read the file depends on whether you know in advance the format of the columns in the CSV file.
If you know the format in avvance (you should), then it is rather simple. If the cell is a string then
file >> str;
otherwise the cell is a double
cin >> dbl;
With a CSV file, the first row typically contains labels for each column, so you would want to handle this separately.
If you don't know the format of the CSV file in advance, then you have a much harder problem. You need to read each cell, determine it type, convert it if necessary and then store it appropriately.
Based on your previous posts, you know the format and the file in question does have a header row. I'm assuming you want to keep the column labels in the first row.
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
|
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
const int max_columns = 41;
const int max_rows = 24; // Excludes header row
bool parse_header_row (const string & line, vector<string> &labels)
{ stringstream ss(line);
for (int col = 0; col < max_columns; ++col)
{ string lbl;
if (! getline(ss, lbl, ';'))
return false; // some error
labels.push_back (lbl);
}
return true;
}
bool parse_data_row (const string & line, double data[max_columns])
{ stringstream iss(line);
string temp;
for (int col = 0; col < max_columns; ++col)
{ // get one column
if (! getline(iss, temp, ';'))
return false; // some error
stringstream convertor (temp);
convertor >> data[col];
}
return true;
}
int main ()
{ vector<string> labels;
double data[max_rows][max_columns];
ifstream file("C:\\file.csv");
string line;
if (! getline(file, line))
{ // handle error
return 0;
}
if (! parse_header_row (line, labels))
{ // handle error
return 0;
}
// Now handle the data rows
for (int row = 0; row < max_rows; ++row)
{ if (! getline(file, line))
{ // handle the error
return 0;
}
if (! parse_data_row (line, data[row]))
{ // handle the error
return 0;
}
}
}
|
Note: You're assuming the file has only 25 rows (including the header row) and 41 columns. This may be a valid assumption for the problem at hand, however, a more general solution would accomodate a variable number of rows and columns. Using vectors rather than a fixed array accomodates this flexibility.