Input file question

Hi, everyone! I'm working on a topological sort problem. I have to read in a text file which contains the information of the graph and output the result to another txt file.

In the input file there are "groups" of data as below(below is one group):
28
19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79 82 85 88 91 94 97 100
26
43 > 37
61 > 40
46 > 19
49 > 94
37 > 79
85 > 19
88 > 34
49 > 37
49 > 76
58 > 37
82 > 37
73 > 97
85 > 70
28 > 79
22 > 70
61 > 91
82 > 61
82 > 67
37 > 31
52 > 76
73 > 31
82 > 28
70 > 37
64 > 31
49 > 31
82 > 79
......


The first integer (28) is the amount of vertices of the graph, followed by the No. of each vertex (19 22 25 28 ... 100)
The next integer (26) is the amount of edges of the graph, followed by the corresponding amount of edges. For instance, 43 > 37 means the directed edge points from 43 to 37.

However, I don't know how to read in this file by ifstream.
Thanks for your help in advance!
Last edited on
Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main()
{


	ifstream input("FILENAME");

	int numberOfVertices;

	input >> numberOfVertices;
	cout << "Num vertice: " << numberOfVertices << '\n';

	vector<int> allTheVertices;

	for (int i = 0; i < numberOfVertices; ++i)
	{
		int vertice;
		input >> vertice;
		allTheVertices.push_back(vertice);
		cout << vertice << ' ';
	}

	int numberOfEdges;
	input >> numberOfEdges;
	cout << '\n' << numberOfEdges << ' ';

	for (int i = 0; i < numberOfEdges; ++i)
	{
		int from;
		int to;
		char throwaway;
		input >> from >> throwaway >> to;
		cout << from << " to " << to << '\n';
	}
}


I leave it to you to check for errors opening the file, dealing with the file being wrongly formatted, and what to actually do with the numbers.

Last edited on
Thanks a lot, that works :)!
Topic archived. No new replies allowed.