Confused about Dynamic Arrays + File Input

Aug 11, 2013 at 9:26pm
I'm working on a small project that basically works like this: the user inputs a text file (via command line). The text file is a list of space separated numbers. I want to read over that list and put the numbers in an array (or an array). I'm just confused about how to create that array. My understanding of reading text files in pretty shaky.

1
2
3
4
5
6
I guess the logic behind the initial code would be something like: 

while there are still numbers to read;
add to back of array

but how do I read over each number in the text file?
Aug 11, 2013 at 10:52pm
closed account (N36fSL3A)
Well. You could use vectors. If you don't want to, pointers can be used as dynamic arrays. For a challenge you could write your own vector class.

1
2
3
4
5
6
7
8
9
10
#include <vector>

int main()
{
    std::vector<int> nums;

    nums.push_back(10); // Add an element.

    return 0;
}
Aug 12, 2013 at 12:35am
Thanks, I understand that aspect of vectors and using pushback. I guess what my problem is looping over a text array of an unknown size and putting each number in a container (2d array or vector)
Aug 12, 2013 at 2:46am
You don't even need to know the size, you can just let the size determine itself.

For each row, read in the entire line to a string and do input with a std::istringstream to extract each individual element. When there's no more data move on to the next row. When there's no more rows, you're done.
Aug 12, 2013 at 3:23am
closed account (N36fSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>
#include <string>

int main()
{
    std::ifstream input("input.txt");
    std::vector<std::string> container;

    if(input)
    {
        std::string buffer;
        while(std::getline(input, buffer))
        {
            container.push_back(buffer);
        }
    }
    input.close();
    return 0;
}


Something along those lines. Basically it loops through until it's unable to get a line (If it hits the end of the file), and pushes back the string.

:D
Last edited on Aug 12, 2013 at 3:24am
Aug 12, 2013 at 3:35am
@Lumpkin close but you forgot to split the string to get each element. The OP specifically mentioned 2D ;)
Aug 12, 2013 at 2:09pm
closed account (N36fSL3A)
Shouldn't be much of a modification. I think you can have 2D vectors like this

std::vector<std::vector<int>> vector2d;
Topic archived. No new replies allowed.