0

The file does open and I get the message "File opened successfully". However I can't input data from the array in file "random.csv" into my inputFile object.

The data in random.csv is:

Boston,94,-15,65

Chicago,92,-21,72

Atlanta,101,10,80

Austin,107,19,81

Phoenix,112,23,88

Washington,88,-10,68

Here is my code:

#include "main.h"

int main() {

    string item; //To hold file input
    int i = 0;
    char array[6];
    ifstream inputFile;
    inputFile.open ("random.csv",ios::in);

    //Check for error
    if (inputFile.fail()) {
        cout << "There was an error opening your file" << endl;
        exit(1);
    } else {
        cout << "File opened successfully!" << endl;
    }

    while (i < 6) {
        inputFile >> array[i];
        i++;
    }

    for (int y = 0; y < 6; y++) {
        cout << array[y] << endl;
    }


    inputFile.close();

    return 0;
}
teukkam
  • 4,267
  • 1
  • 26
  • 35
u u
  • 1
  • 2

1 Answers1

0

Hello and welcome to Stack Overflow (SO). You can use std::getline() to read each line from the file, and then use boost::split() to split each line into words. Once you have an array of strings for each line, you can use a container of your liking to store the data.

In the example below I've used an std::map that stores strings and a vector of ints. Using a map will also sort the entrances using the key values, which means that the final container would be in alphabetical order. The implementation is very basic.

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include <ctype.h>

typedef std::map<std::string,std::vector<int>> ContainerType;

void extract(ContainerType &map_, const std::string &line_)
{
    std::vector<std::string> data;

    boost::split(data, line_, boost::is_any_of(","));

    // This is not the best way - but it works for this demo.
    map_[data[0]] = {std::stoi(data[1]),std::stoi(data[2]),std::stoi(data[3])};
}

int main()
{
    ContainerType map;

    std::ifstream inputFile;
    inputFile.open("random.csv");

    if(inputFile.is_open())
    {
        std::string line;
        while( std::getline(inputFile,line))
        {
            if (line.empty())
                continue;
            else
                extract(map,line);
        }
        inputFile.close();
    }

    for (auto &&i : map)
    {
        std::cout<< i.first << " : ";
        for (auto &&j : i.second)
            std::cout<< j << " ";
        std::cout<<std::endl;
    }
}

Hope this helps.

Constantinos Glynos
  • 2,952
  • 2
  • 14
  • 32