I'm only a beginner and have yet to cover any #<sstream> and #<iterator> stuff.
I known that I have 8 lines that need to be stored in 8 vectors. Is there anyway to read just the first line then store it in a named vector. Then the second to another named vector etc???
> yet to cover any #<sstream> and #<iterator> stuff.
If you know how to use file stream, you already know how to use string stream. Sans the <iterator> stuff:
1 2 3 4 5 6 7 8 9 10 11
std::vector<int> parse_line( std::string line )
{
std::vector<int> result ;
std::istringstream stm(line) ;
int value ;
while( stm >> value ) result.push_back(value) ;
return result ;
}
#include <iostream>
#include <vector>
#include <cctype>
#include <fstream>
bool read_one( std::istream& stm, int& value ) // read the next integer
{
char c ;
// extract and throw away characters till a non-whitespace or new line is extracted
// or there is an input failure.
while( stm.get(c) && c != '\n' && std::isspace(c) ) ;
if( c == '\n' ) returnfalse ; // extracted new line; nothing more to read from this line
stm.putback(c) ; // extracted a non-whitespace character, put it back
returnbool( stm >> value ) ; // and try to read an integer
}
std::vector<int> read_line( std::istream& stm ) // read all integers in one line
{
std::vector<int> result ;
int value ;
while( read_one( stm, value ) ) result.push_back(value) ;
return result ;
}
int main()
{
constchar* const path = "test.txt" ;
// create a test file
{ std::ofstream(path) << "1 2 3 4 5 \n 3 4 5 6 7 4 7 7 \n 1 5 7 7 4 3 4 \n" ; }
std::ifstream file(path) ;
std::vector<int> a = read_line(file) ;
std::vector<int> b = read_line(file) ;
std::vector<int> c = read_line(file) ;
for( constauto& vec : { a, b, c } )
{
std::cout << "[ " ;
for( int value : vec ) std::cout << value << ' ' ;
std::cout << "]\n" ;
}
}
Sorry probably should have made clearer, that the method of storing the number in the first post has been completely changed. Instead of each 1 vector on 1 line, 1 vector per column.
So the number of vectors is known, but the number of elements in each vector is variable, but there will be the same number of elements in all the vectors.
This problem has been blowing my mind all week, thanks for taking a look!