Empujar un vector dentro de otro vector

I have a file that goes like this:

287 2352
987 4313 3253
235 34325 432 123

Basically I want to reproduce this file. I am trying to import a line at a time, extract the numbers, and push them into vectors. Each vector is pushed into a larger vector.

int main(int argc, char* argv[])
    int sum = 0, one = 0, two = 1;
    std::string line, number;
    std::vector<int> vec;
    std::vector<std::vector<int>> bigvec;
    auto k = vec.begin();
    std::ifstream in(argv[1]);
    while(in >> line) {
        std::istringstream is(line);
        while(is >> number) {
        while(!vec.empty()) {
        std::cout << std::endl;
    return 0;

My code though, when I print the result, seems to put each number in it's own vector instead of reproducing the file.

So my output is


Parece que la linea

while(is >> number) {

pushes one number and then exits the loop.

¿A dónde me estoy yendo mal?

preguntado el 09 de septiembre de 13 a las 21:09

while(!vec.empty()) { vec.pop_back(); } ¡Eww! vec.clear(); hará precisamente eso. -

std::string number; ¡Eww! int number; while(is >> number) {vec.push_back(number);} lo hará bien. -

Was going to say the same thing :) -

2 Respuestas

while(in >> line) reads next por el temor from the input. Use getline(in, line) if you want to read a whole línea.

There are multiple optimizations that you can add to your code. For instance instead of using stoi on the string you've read you can read an integer from the input stream. Also instead of popping the vector's elements one by one you can simply call clear.

Respondido el 09 de Septiembre de 13 a las 21:09

Tu problema radica aquí:

while(in >> line)

C++ by defult reads until it encounters interval or new line. In your case it encounters interval before new line. If you want to take the whole line take:

getline(cin, line);

Respondido el 09 de Septiembre de 13 a las 21:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.