Reading a vector of unknown length

Hi, I'm writing a program where I'm instructed to prompt the user for two vectors, both of unknown length and type double, which will then be sorted into ascended order and finally merged into one vector. I think I'm comfortable with writing the rest of the code but I'm hung up on how to enter the initial vectors without knowing the length. We were specifically instructed not to prompt the user for the length of the vector, and to read the inputs from a single line separated by spaces. Also, the for/while loop for reading the inputs cannot be ended by a certain character like '0' or '/'. I can read from the same line with this code, but as you can see it's still cut off when i=10.

this is the code for reading the elements from the same line and storing them in an array. Is there some other way to do this?

printf("Enter the elements of the first vector:");

scanf( "%[0-9a-zA-Z ]", array1 );

for(i=0;i<10;i++)
{
char *s = array1;
vector1[i]=strtof(s, &end);
s=end;
}
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
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<double> parse_line( const std::string& line )
{
    std::vector<double> result ;

    std::istringstream stm(line) ; // input stream that reads from the string
    double value ;
    while( stm >> value ) result.push_back(value) ; // add each value read to the vector

    return result ;

}

std::vector<double> get_from_line( std::istream& stm = std::cin )
{
    std::string line ;
    std::getline( stm, line ) ; // read a complete line into a string

    return parse_line(line) ; // parse the line and return the result
}

int main()
{
    for( double v : get_from_line() ) std::cout << v << '\n' ;
}

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