Reading in an unknown number of integers separated by spaces into one vector per line

StackOverflow https://stackoverflow.com/questions/20278655

  •  06-08-2022
  •  | 
  •  

문제

Each line of my file consists of an unknown number of integers, which are separated by spaces. I would like to read in each line as a vector of those integers.

Here is an example of such file:

11 3 0 1
4 5 0 3
2 3 4 1
23 4 25 15 11
0 2 6 7 10
5 6 2
1
11

I've been able to read in small amounts of data successfully using the following method (Note that outer_layers is a vector that contains these vectors I'm trying to populate):

for (int i = 0; i < outer_layers.size(); i++)
{
    while (in >> temp_num)
    {
        outer_layers[i].inner_layer.push_back(temp_num);
        if (in.peek() == '\n')
            break;
    }
}

However, when I'm trying to read in larger amounts of data, sometimes it'll read in two lines under one vector. In one of the files, out of 24 lines, it read two-liners on two occasions, so last two vectors did not have any data.

I can't wrap my head around it. Any ideas what I'm doing wrong?

EDIT: Something interesting I've noticed in some of the lines of the trouble-maker file is this:

Let's say there are three lines.

23 42 1 5
1 0 5 10
2 3 11

Line #1 reads in just fine as 23 42 1 5; however, line #2 and #3 get read together as 1 0 5 10 2 3 11.

In Notepad++ they look just fine, each on their own lines. However, in Notepad, they look like this:

23 42 1 51 0 5 10 2 3 11

If you notice, the 5 (last integer of line #1) and 1 (first integer of line #2) are not separated by spaces; however, 10 and 2 are separated by a space.

I've noticed that behavior on any double-read-in lines. If they are separated by a space, then they're both read in. Not sure why this is occurring, considering there should still be a new line character in there for Notepad++ to display the on separate lines, am I right?

도움이 되었습니까?

해결책

I'm not sure how your outer_layers and inner_layers is setup, but you can use std::getline and std::stringstream to fill your vectors something like this :

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

    std::ifstream fin("input.txt");

    std::string line;
    int i;
    while (std::getline( fin, line) ) //Read a line 
    {
       std::stringstream ss(line);

       while(ss >> i) //Extract integers from line
         vec.push_back(i);

       V.push_back(vec); 
       vec.clear();

    }

  fin.close();

  for(const auto &x:V)
  {
    for(const auto &y:x)
      std::cout<<y<<" ";
    std::cout<<std::endl;
  }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top