Read txt file line by line write to vector

Hi, I need to read a text file which has various lines containing integers. I need to write those integers separately in a vector. Example, the first line of the text file contains 3 9 8 7 6 so vector[4]=3, vector[3]=9, vector[2]=8 and so on. Next read the second line 4 1 2 3 4 5 and write to another vector vector[5]=4, vector[4]=1...

I tried the code below but it will write from the second line, the whole line in one vector index.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int str; // Temp string to
    cout << "Read from a file!" << endl;

    ifstream fin("functions.txt"); // Open it up!
	
    string line;
    // read line count from file; assuming it's the first line
    getline( fin, line );
    // convert the string to an integer
    stringstream ss( line );
    int n;
    ss >> n;
    // reserve vector size to line count
    vector< string > function( n );
    // read each line and put it into the vector in the reserved indicies
    int i = 0;
    while( i < n && getline( fin, line ) ) {             // 
        function[i] = line;
        i++;
    }


Thanks in advance...
Something like this:

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
43
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <algorithm>

std::vector<int> ints_in_reverse( const std::string& str )
{
    std::istringstream stm(str) ; // input stringstream to read from the line

    // create a vector containing inters in the line (left to right)
    using iterator = std::istream_iterator<int> ;
    std::vector<int> seq { iterator(stm), iterator() } ;

    std::reverse( std::begin(seq), std::end(seq) ) ; // reverse the vector

    return seq ; // and return it
}

std::vector< std::vector<int> > reverse_read_lines( std::istream& stm )
{
    std::vector< std::vector<int> > result ;
    std::string line ;

    while( std::getline( stm, line ) ) result.push_back( ints_in_reverse(line) ) ;

    return result ;
}

int main()
{
    std::istringstream file( " 3 9 8 7 6\n"
                             "4 1 2 3 4 5\n"
                             "0 1 2 3 4 5 6 7 8 9\n" ) ;

    const auto vectors = reverse_read_lines(file) ;

    for( const auto& line : vectors )
    {
        for( int v : line ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/293c30ce6dd2a732
Topic archived. No new replies allowed.