Getting Separate Vectors from txt File

Hi Guys,

I am struggling a lot at this point and could really use some help. I have the following code that works with getting data from a text file and storing it in a vector P. I need to make it so that I can get the data from the file but store it in different vectors for instance if I have the following text file:

2
1000 2 4 6 980
1000 5 90 700

I want to pull the data into my code as
P[0] = 2
P[1] = 1000 2 4 6 980
P[2] = 1000 5 90 700

I have am not sure how to make this happen. I do not want this to be pulled in as a matrix but as separate vectors that can then be manipulated with other code as necessary. Here is the code I have currently:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cmath>
#include <vector>
#include <fstream>

using namespace std;

vector <double> get_data(){

	double value_just_read_from_file;
	vector <double> P;

	ifstream input_file ("Data.txt");

	if (input_file.is_open ())
	{
			while(input_file >> value_just_read_from_file)
			{
				P.push_back(value_just_read_from_file);
			}
	}
	else
			cout << "Input_file_Data.txt_does_not_exist_in_PWD" << endl;

	cout << "Vector_P_has_" <<P.size() << "_entries, _and_They_are : " <<endl;
	for (size_t i = 0; i < P.size(); i++)
				cout << P[i] << " ";
	cout << endl;
	return(P);
}

int main(){
double k;
	vector <double> P;
	vector <double> CF;
	P = get_data(0);
	k = P[0];           //P[0] of the data is the number of vectors left in the data file
                   //I am feeding k back through the function in order to use the information on the size to 
                   //get the rest of the vectors out of the data.
	CF = get_data(k);
	
}


With the data I showed above this code has output:

2 1000 2 4 6 980 1000 5 90 700

Please help me. Any suggestions at all are very very appreciated. Thanks in advance!

Also the length of the data file is not know, ie. I do not know ahead of time how many vectors are in the data file. The first input however is ALWAYS the amount of vectors that will follow. So the 2 in the first line of the data tells you that there will be two vectors.
Last edited on
You need to:
1. Read the number of lines
2. For each line:
2a: Read the entire line into a string
2b: Use a stream (a string stream) read the numbers and add them to a container
2c: Add the container to your container of containers
Topic archived. No new replies allowed.