mercredi 6 novembre 2019

Read in 3 column csv file using C++ 11

I have a csv file that looks like this:

| Start Time(s) | Start Floor | End Floor |
|:-------------:|:-----------:|:---------:|
|       41      |      54     |     55    |
|       43      |      30     |     74    |
|       88      |      87     |     32    |
|       93      |      35     |     55    |
|      121      |      35     |     4     |

I am trying to read the csv line by line, and print out:

Current Start Time: 41
Current Start Floor: 54
Current End Floor: 55

Current Start Time: 43
Current Start Floor: 30
Current End Floor: 74
...etc

Instead, I am getting:

Current Start Time: S
Current Start Floor: t
Current End Floor: a


Current Start Time: 4
Current Start Floor: 1
Current End Floor: ,


Current Start Time: 4
Current Start Floor: 3
Current End Floor: ,


Current Start Time: 8
Current Start Floor: 8
Current End Floor: ,

Why am I not printing out the three values in the columns? How can I properly access the columns of what I am reading in? (I can either read it in line-by-line, or all at once, and access the rows, column by column, later on)

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
    //cout << "Hello world" << endl;

    string line; // for reading in the file as a string

    // open the .csv file
    ifstream fin("D:\\Grad School\\Fall 2019\\EN.605.604.81.FA19 - OO Programming with C++\\Project 7\\data.csv");
    // while it still has lines
    while(getline(fin, line)){
        // set curr to the current value
        cout << "Current Start Time: " << line[0] << endl;
        cout << "Current Start Floor: " << line[1] << endl;
        cout << "Current End Floor: " << line[2] << endl;
        cout << "\n" << endl;
    } //end while

}

Aucun commentaire:

Enregistrer un commentaire