I want to read sets of numbers separated by spaces.
The sets are separated by 0.
Each set contains between 2 and 1000 numbers.
The last line of the input is a lone 0.
After I got one set I will calculate something with the numbers (except the 0), output the result and then I won't need that set anymore.
I tried with getline and delimeter 0, but it will also cut if a number has a 0 as part of it, like 105.
If I try to use ' 0' as delimeter it warns me about multi character constant.
I tried to just cin >> myVector[i] until myVector[i] is 0, but that leads to address boundary error.
I would greatly appreciate any ideas on how to make this work.
#include <ciso646>
#include <iostream>
#include <vector>
typedef std::vector <int> collection;
bool read_collection( std::istream& ins, collection& xs )
{
xs.clear();
int x;
while (ins >> x and x) xs.push_back( x );
return ins.good();
}
int main()
{
// Read the first two collections
collection xs, ys;
read_collection( std::cin, xs );
read_collection( std::cin, ys );
// Ignore the final collection
{
collection foo;
read_collection( std::cin, foo );
}
These functions do not assume that each collection is on a single line. (If they did then there would be no need for the semaphore zero to terminate them.)
Now, the following input:
2 3 5 7 11 0
-1 2 -3 4
-5 6 -7 8
0 0
Thanks a lot Duthomhas, that did help.
I had to modify the main() a bit so I can have any amount of sets as input, as I don't know that beforehand either ;)
Since I don't need the vectors after my calculations I just overwrite it and check if it has at least 2 numbers to avoid writing a 0 at the end.