Take the 2-minute tour ×

I know the topic has been discussed a lot but I still don't really get it. Admittedly I am pretty new to C++ coding, so please go easy on me :)

Anyhow: I have this examplatory csv file:


I need an array with unknown dimensions a priori, since the csv will expand unpredictably -> dynamic array in both x and y direction.

This is what I managed to do so far:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

int main()
    vector<vector<double> > values;
    vector<double> valueline;
    ifstream fin("in.csv");
    string item;
    for (string line; getline(fin, line); )
        istringstream in(line);

        while (getline(in, item, ','))


It appears to be doing the job, but if I try to output the array or parts of it, I get strange results. For example cout << values[0][3] << endl; yields 1.63042e-322. values[0][4] yields 91.5919. Also sizeof(values[0]) is 24.

Am I doing something I am not supposed to here?

Any help would be great! Thanks

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Try using .at() operator to see whether you aren't reading beyond the end of the vector? values[0][3] is the fourth element of the first line, which doesn't exist in your input?

You probably want to do:

std::cout << values[3][0]; // Fourth line, first element;


std::cout << values.at(3).at(0); // Fourth line, first element;

Index operators on vectors do not do bounds checking. This is for performance reasons. You are reading out of bounds, and thus you get the strange numbers. at() throws a std::out_of_range exception.

share|improve this answer

Using sizeof on a vector is mostly useless -- it tells you the size of the top-level vector data structure (generally two size_ts and a pointer) in bytes, which is not terribly useful. If you want the size of the vector, use the size method -- values[0].size() tells you how many values are on the first line.

share|improve this answer

Your Answer


