-2

So I have a file with 4 lines which reads as follows:
1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

I'm trying to read in all that and store in 2D int array. I can only read in the first line when I use the stoi function. Any suggestions on how I can read all the lines.

Patwie
  • 4,360
  • 1
  • 21
  • 41
Robo
  • 1
  • 1
  • You probably want to use std::getline(file,mystring); and use std::istringstream on the string, – drescherjm Jun 01 '20 at 15:54
  • 2
    Related: [https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – drescherjm Jun 01 '20 at 15:57
  • I recommend searching the internet for "C++ read file comma separated 2d array". There are already a plethora of examples on how to do this. – Thomas Matthews Jun 01 '20 at 16:45
  • Can you post your original code, so it is possible to analyze it and say sth about it? Else we can just post a "best guessing solution". It's better to have sth to start with instead of making a complete new attempt to answer the question. – Wör Du Schnaffzig Jun 01 '20 at 20:21

1 Answers1

1
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>

std::vector<std::vector<int>> get2DVector(int n, std::string filename)
{
    std::vector<std::vector<int>> result(n);

    std::ifstream input(filename);

    std::string s;
    for (int i = 0; i < n; i++)
    {
        std::getline(input, s);
        std::istringstream iss(s);

        std::string num;
        while (std::getline(iss, num, ','))
            result[i].push_back(std::stoi(num));
    }

    return result;
}

int main()
{
    auto vec = get2DVector(4, "input.txt");

    for (auto& v : vec)
    {
        for (int i : v)
            std::cout << i << ' ';
        std::cout << '\n';
    }
}

input.txt:

1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

Output:

1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

I used std::vector here since the length of each array may vary. If the length of each array is the same, you can just use normal arrays. Don't recommend it tho.

StackExchange123
  • 1,871
  • 9
  • 24