-2

I need to read values from an text file. There is multiple values on each line, and there is over a couple of thousand lines in the text file.

I want to save each individual value to a vector, but i dont know how i should make the program to read every value on the same line.

I tried to use getline, but it takes the whole line and saves it.

Grateful for every help i can get!

Gruffis
  • 1
  • 3
  • I believe a solution could involve getline and probably istringstream. Can you please add the code that you tried. At StackOverflow if you show your attempt you will be way more likely to get help fixing it. – drescherjm Dec 10 '20 at 13:34

1 Answers1

0

You can read all numbers and store them all in one vector with

int number;
std::vector<int> vec;

while (file >> number)
    vec.push_back(number);

e.g.:

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>

int main() {
    //std::ifstream file("file.txt");
    std::stringstream file(R"(1 2 3
4 5 6 7 8 9
10 11
12
13
14 15 16)");
    int number;
    std::vector<int> vec;

    while (file >> number)
        vec.push_back(number);
    
    std::cout << vec.size();
}

vec contains all 16 numbers.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • vec.push_back(number), takes the number from the input file and pushes it into the vector "vec"? – Gruffis Dec 10 '20 at 14:19
  • @Gruffis `vec.push_back(number)` puts `number` into the vector. `file >> number` reads the number from file stream (or string stream in my example). – Thomas Sablik Dec 10 '20 at 14:20
  • Okay, i understand. Thank you so much! – Gruffis Dec 10 '20 at 14:23
  • i just ran into some problems. Push back vector works perfectly fine, the problem is that when i test how large the vector is with sizeof() , it says 12, it should be around 6000 – Gruffis Dec 10 '20 at 15:58
  • @Gruffis `sizeof` gives you the compile time size of an object. This size won't change during runtime. A vector uses dynamically allocated memory. You get the number of elements with `vec.size()` as you can see in my example. – Thomas Sablik Dec 10 '20 at 16:04