-2

A file contains the following data:

10 11 12 13 14 15
16 17 18 19 20 21

I have read the first line into an integer array. Now I want to read the second line of numbers into a second array. How can I accomplish the second array thing? I've used the following code to read in the first line:

while(!mystream.eof())
{
    mystream>>a[i];
    i++;
}
NetVipeC
  • 4,402
  • 1
  • 17
  • 19

2 Answers2

1

As you haven't included any code, I guess you just need a hint. So I will show some ways you can achieve this. Feel free to ask for more details and add code.

You can read every line in a std::string and parse it. You can choose between multiple parsing options, like knowing the string format (2 digit numbers followed by a space) and using something like v[i] = (str[a] - '0') * 10 + str[a + 1] - '0'; (you need to figure what is the value of a for the i-th integer), or you can use a combination of string::find to search for spaces and string::substr to split it and something like itoa() to obtain an integer. Or, you can use sscanf(), even if it is a C function, to parse the string.

Paul92
  • 8,827
  • 1
  • 23
  • 37
1

I'd start by reading a line of text into a std::string using std::getline.

I'd then initialize a std::istringstream from that string, and parse individual ints from that line and put them into a std::vector<int>. I'd probably do this using std::istream_iterator<int>s, and initialize the vector from a pair of them.

I'd repeat that process as long as std::getline succeeded.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111