C++ program that takes a graph as an adjacency list from a text file, creates a
ID: 3871648 • Letter: C
Question
C++ program that takes a graph as an adjacency list from a text file, creates a graph from it, then topologically sorts it. I need help reading the file properly. The format of the file is:
Where the first int of each line is a vertex, and the following ints are the vertices it has an edge to.
I have something like this so far:
void buildGraphFromFile(string filename, int numLines, int arr[10][10])
{
ifstream fileStream;
fileStream.open(filename);
while (!fileStream.is_open())
{
fileStream.close();
fileStream.clear();
system("cls");
cout << "Error opening file";
system("pause");
}
int nextInt;
for (int i = 0; i < numLines; i++)
{
for (int j = 0; j < 10; j++)
{
fileStream >> nextInt;
arr[i][j] = nextInt;
}
}
fileStream.close();
}
int main() {
string file = selectInputGraph(); //gets input file from user
int lines = countInputFileVertices(file); //gets number of lines in file
Graph graph(lines);
int arr[10][10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
arr[i][j] = 0;
}
}
buildGraphFromFile(file, lines, arr);
return 0;
}
Thank you!
Explanation / Answer
void buildGraphFromFile(string filename, int numLines, int arr[10][10])
{
ifstream fileStream;
fileStream.open(filename);
while (!fileStream.is_open())
{
fileStream.close();
fileStream.clear();
system("cls");
cout << "Error opening file";
system("pause");
}
int nextInt;
for (int i = 0; i < numLines; i++)
{
for (int j = 0; j < 10; j++)
{
fileStream >> nextInt;
arr[i][j] = nextInt;
}
}
fileStream.close();
}
int main() {
string file = selectInputGraph(); //gets input file from user
int lines = countInputFileVertices(file); //gets number of lines in file
Graph graph(lines);
int arr[10][10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
arr[i][j] = 0;
}
}
buildGraphFromFile(file, lines, arr);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.