snipshow7
snipshow7

Reputation: 87

read .csv file and store into arrays using only <iostream> c++

Hello I am wondering what the most efficient way would be to read a .csv file and store each comma separated item into its own array or variable. I can only use #include <iostream>. I was thinking about maybe using .getLine(), but all i would know is the delimeter and value to store since there is no <fstream> allowed. That being said does anyone know how I could go about this? Thanks in advance!

This is the layout of the file. The first line indicates the umber of rows to be read.

input file

3
2014,Computer Science,Utah,1568,44.9
2014,Marketing,Michigan,23745,983
215,Business Management, Idaho,256,674

code:

int year;
char* major = new char[40];//cant be longer than 40 characters
char* state = new char[40]; 
int enrolled;
int rate;
char p;//for cin.get characters possibly

cin>>rows

for(int i = 0; i <= rows; i++){

HMMMMM?

}

Upvotes: 3

Views: 2131

Answers (1)

kiner_shah
kiner_shah

Reputation: 4641

You can use cin.getline() function which also accepts a delimiter. As for storing the entire csv record, you can define a structure which stores all the fields.

#include <iostream>
#include <cstring>
using namespace std;

typedef struct temp_struct {
    char major[40];
    char state[40];
    float rate;
    int year;
    int enrolled;
} RECORD;

int main() {
    int rows;
    cin >> rows;
    RECORD r[rows];
    char temp[100];
    for(int i = 0; i < rows; i++) {
        cin.getline(temp, 100, ',');
        r[i].year = atoi(temp);

        cin.getline(temp, 100, ',');
        strcpy(r[i].major, temp);

        cin.getline(temp, 100, ',');
        strcpy(r[i].state,temp);

        cin.getline(temp, 100, ',');
        r[i].enrolled = atoi(temp);

        cin.getline(temp, 100);
        r[i].rate = atof(temp);

        cout << r[i].year << " " << r[i].major << " " << r[i].state << " ";
        cout << r[i].enrolled << " " << r[i].rate << endl;
    }
    return 0;
}

For delimiters, the first four delimiters would be , and since the last value rate has no , following it rather there's a \n, no delimiter is specified in the cin.getline() (since default delimiter is \n itself).

I have tested it; here's the link https://ideone.com/ycht1b

Upvotes: 1

Related Questions