0

Suppose I have something along the lines:

#include <iostream>
#include <cstdlib>   
#include <vector>
using namespace std;
const int MAX_EDGES = 4;
... 
int main() {
...
int edges[4];
cout << "Enter the outward-edges for node " << i+1 << ":" << endl;
cin >> edges[0] >> edges[1] >> edges[2] >> edges[3]; 
... 
} 

However, I'm in a situation where each node (which is defined as a struct somewhere above) may not have 4 "outward-edges". Therefore I would like the user to only have to input those edges to which this node is connected and not have to enter -1 or some such to represent no outward edges. For example, right now we might have the input

2
3
-1 
-1 

To represent that node i+1 (we're inside a for loop at the moment) has two outward edges, namely to node 2 and 3. However I would like to be able to make this just 2 3.

Any help appreciated! Cheers.

Bihc
  • 103
  • 5
  • 1
    You might want to avoid a statically sized array in favor of a `std::vector`, with `cin` reading into a `std::back_inserter` for the `vector`. Allows the `vector` to size precisely to the number of values provided. – ShadowRanger Nov 20 '15 at 03:12
  • @ShadowRanger I like the idea. I tried running with it, but am running into problems writing the input into the vector. Can one have `getline (cin, back_inserter(edges)`, where `vector edges;`? Or is the idea to write it into a string and then parse it into the vector? – Bihc Nov 20 '15 at 03:28
  • 2
    If the goal is to parse a set of numbers entered on a single line, yeah, you'd probably want to do something like read in a line, use it to initialize a `std::stringstream`, then use `std::copy` and `std::istream_iterator` with the `back_inserter` to tokenize the inputs and shove them into the `vector`. See [this answer](https://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c#53921) for some demonstrations of tokenizing with `iostream` stuff. – ShadowRanger Nov 20 '15 at 03:36

0 Answers0