-1

So I have a problem about a graph and I have to read from an input file multiple cases and check a propriety. Each case has on the first line n, the number of nodes it has, and on the second line a sequence of integers x y, where (x, y) is an edge. The problem is that I don't know how many edges I have, so I don't know where to stop reading.

Example:

Input File :

5

1 2 1 3 1 4 2 5 3 5 4 5

7

1 2 4 5 2 6

I looked everywhere on the web for a solution, but couldn't find one that works for me. Most of the solutions I found only read strings. I tried to find and stop at '\n' but that didn't worked at all. Int('\n') is 10 on my computer, so it got confused with the 10s from my sequence of edges. And it didn't even read the '\n'.

Community
  • 1
  • 1

1 Answers1

0

Here is a solution:

struct Edge
{
  int x;
  int y;
  friend std::istream& operator>>(std::istream& input, Edge& e);
};

std::istream& operator>>(std::istream& input, Edge& e)
{
  input >> e.x;
  input >> e.y;
  return input;
}

Here's some main code:

int node_quantity = 0;
std::vector<Edge> database;
std::cin >> node_quantity;

// Ignore the newline following the number.
std::cin.ignore(1000, '\n');

// Start at the beginning of the line.
std::string text_line;
std::getline(std::cin, text_line);
// Read in the edges
std::istringstream text_stream(text_line);
Edge e;
while (text_stream >> e)
{
    database.push_back(e);
}

The above code creates an edge structure and overloads operator>> for reading in an edge.

The second code fragment reads in a line of edges and uses a std::istringstream to read all the edges in the text line.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154