Question about loading CSV into arrays

Hi there I am taking an intro c++ class and need some help loading data into arrays. I wouldn't have any problem loading rows into arrays but I need to load columns and have no idea how to do that. Thanks in advance for your help!

//My arrays look like this:

#include <iostream>
#include <fstream>
#include <string>
#include "Military.h"

using namespace std;

#define FILE_IN "MilitaryExpendituresProject.csv"
#define FILE_OUT "MilitaryOutput.txt"


int main()
{
ifstream input;
ofstream output;

string Countries[154];
double Y2002[154];
double Y2003[154];
double Y2004[154];
double Y2005[154];
double Y2006[154];
double Y2007[154];
double Y2008[154];
double Y2009[154];
double Y2010[154];
double Y2011[154];
double Y2012[154];


input.open(FILE_IN);

//my CSV file looks like this:

Algeria,3222,3152,3585,3753,3847,4514,5259,5712,6045,8652,9104
Libya,831,1085,1069,941,885,1338,0,0,0,2800
Morocco,2483,2413,2504,2528,2603,2904,3101,3319,3343,3582
Tunisia,500,510,548,571,525,567,586,602,623,746
Angola,1989,1893,2682,3151,2763,3741,3640,3894,3647,3827
Benin,55.1,60,60.9,60.9,0,65.9,0,0,0,79.4
Botswana,429,396,359,354,390,417,402,381,371,345
Burkina Faso,67.9,80.8,84.3,90.8,112,122,112,134,139,153
Burundi,83.9,79.7,76.1,63.6,63.9,53.4,0,0,0,57.7
Cameroon,285,303,299,325,341,353,358,383,347,372
Cape Verde,8.9,9.2,9.8,9.3,9.3,8.8,9,9.1,9.7,0
Central African Rep.,23.3,21.8,21.6,0,22.6,31.8,37,54.8,0,0

//So I have a string array for countries
//and double arrays for each year
//How do I load the arrays with the columns instead of the rows?
//Thanks!!

I do not understand these definitions

double Y2002[154];
double Y2003[154];
double Y2004[154];
double Y2005[154];
double Y2006[154];
double Y2007[154];
double Y2008[154];
double Y2009[154];
double Y2010[154];
double Y2011[154];
double Y2012[154];

If 154 is the number of lines in the input file then each line contains several fields. And where are you going to store these fields?
Or each array denotes one field in a line?
Last edited on
Sorry for the confusion. Each array represents one field in each line. So each line has 12 elements. One country and the amount spent by that country for the last 11 years. I have 154 countries. Does that make sense?

EDIT* The top row looks like this in the CSV:

Country,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012
Last edited on
In this case I would define the record the following way

std::map<std::string, std::array<double, 11>> record;

At least it would be better to define one two-dimensional array

For example

double values[154][11];

You should use function std::getline that to read each field of a line and then convert and store numerical values in corresponding elements of the array.
Last edited on
I thought about using a multi-dimensional array but our teacher says she only wants us to use one-dimensional arrays. I suppose I will just use a 2D array anyway. Thanks for your help!
Topic archived. No new replies allowed.