How To Read/Store Two Columns of Numbers From File of Unknown Size

Hi, I've looked really hard and can't find a straightforward way to use an array or vector to store the elements from files, each of varying/unknown length. Each file simply has two sets of numbers per row and so they need to be stored together like an ordered pair. Here's what I came up with:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{

std::vector<vector<double>>coordinates;

ifstream inFile("data1.txt");

double x, y;

while (!inFile.eof())
	{
		inFile>>coordinates[x][y];
		coordinates.push_back(coordinates);
	}


First of all, am I going in the right direction with this? Is a vector what I need? Am I storing the numbers from the file correctly, using an array?

The way it's written now, it puts a red line under the dot after "coordinates" in the push_back function. I guess I don't really understand the push_back function, but I'm assuming it doesn't make sense to have the name of the vector before the dot, but I'm not sure what else to do. I tried using a different name for the vector and doing a separate "double coordinates;" declaration, but if I'm trying to use coordinates as an array, then that doesn't work. Obviously I can't declare an array if I don't know the size. So I'm stuck and keep running in circles because I thought the point of a vector was to basically use an array of unknown size?
Last edited on
Without testing

1
2
3
4
while ( inFile >> x && inFile >> y )
{
   coordinates.emplace_back( { x, y } );
}   

Topic archived. No new replies allowed.