-1

Let's say I have a .in file with the first line of data "3 59 98" and the second line of data "8 52 77 45".

I'm trying to read each line of integers into a list. I already understand how to make a list and put numbers in the list. What I am having trouble with is how to get the first line of numbers into a list object.

the following is an idea of what I have so far:

// in is a filestream object
int a
while (in >> a)
{
     integer_list.push_back(a);
}

I know this doesn't work because it puts both lines of numbers into one list.

Any suggestions?

Brandon Tiqui
  • 1,429
  • 3
  • 17
  • 35
  • No more duplicates. This has been answered a hundred times already. Please don't post answers to this. – Kerrek SB Feb 20 '13 at 13:16
  • @KerrekSB I removed my answer. Maybe we should try to edit the original so that it is easier to find? – Ivaylo Strandjev Feb 20 '13 at 13:18
  • How do I close this question? – Brandon Tiqui Feb 20 '13 at 13:23
  • @Brandon: don't worry, once enough people vote it as a duplicate, it'll be closed automatically. You can leave it around, though, so that when people search for it they'll be directed one of the other questions. – Kerrek SB Feb 20 '13 at 13:50
  • @IvayloStrandjev: I think there are at least 20 "originals" of this. I just selected one I rememebered, but it'd be easy to find many others. We don't really have a "canonical answer" section... – Kerrek SB Feb 20 '13 at 13:51

2 Answers2

1

Use getline to read a whole line and then create std::istringstream from this line. Read from the std::istringstream the numbers in the list just as if you are reading from a file stream.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
-2

What you need to do is to create a list of integer lists, although in C++ you would prefer to use a vector.

std::vector< std::vector<int> > list_of_integer_lists;

then for each line you would add a new list or vector.

list_of_integer_lists.push_back( std::vector<int>() );

and for each line you add the numbers to the last list.

list_of_integer_lists.back().push_back( number );
Thomas
  • 4,980
  • 2
  • 15
  • 30