I am trying to print a matrix representing Graph nodes and edge weights using for loops. All rows after the first one work as expected, but the print of the Node names of columns is behaving very strange, I am completely lost after trying multiple different methods. Here is the 'bugged' code and output.
Code:
void Graph::print_graph_matrix(void)
{
std::cout << "\n";
int i, j;
for(i = 0; i < nodes.size(); i++)
{
std::cout << "\t" << nodes[i];
}
std::cout << "\n";
for(i = 0; i < nodes.size(); i++)
{
std::cout << nodes[i];
for(j = 0; j < nodes.size(); j++)
{
std::cout << "\t" << edges[i][j];
}
std::cout << "\n";
}
}
Output:
D
A 0 0 0 0
B 0 0 0 0
C 0 0 0 0
D 0 0 0 0
However the top column labels should print
A B C D
When I tried debugging it within the code (by printing out the value of i itself), the first time i printed out it printed out as 3, instead of 0, my target starting index.
I've never seen anything like this, please help me understand what is going on here. Thank you!
EDIT: Other parts of my code are being asked for as this may be happening elsewhere.
Main:
int main()
{
clear_screen();
int graph_num;
std::string filename;
std::cout << "How many graphs would you like to create?\n";
std::cin >> graph_num;
std::cin.ignore();
std::fstream files[graph_num];
Graph * graphs[graph_num];
for(int k = 0; k < graph_num; k++)
{
graphs[k] = new Graph();
std::cout << "\nEnter the name of file " << k+1 << " to read: ";
std::cin >> filename;
std::cin.ignore();
files[k].open(filename.c_str());
if(files[k].fail())
{
std::cout << "\nError opening file '" << filename << "'...\n";
return -1;
}
else
{
std::cout << "\nSuccess opening '" << filename << "'!\nSetting graph...\n";
graphs[k]->set_graph(files[k]);
graphs[k]->print_graph_matrix();
}
}
for(int j = 0; j < graph_num; j++)
{
files[j].close();
}
}
set_graph function:
void Graph::set_graph(std::fstream &fin)
{
std::string line;
std::vector<int> row;
while(getline(fin, line))
{
if(isBlank_str(line))
{
std::cout << "Nodes read in successfully!\n";
break;
}
else
{
nodes.push_back(line);
node_num++;
}
}
while(getline(fin, line))
{
//set edges here
edge_num++;
if(fin.eof())
break;
}
//initialize an empty row
for(int i = 0; i < node_num; i++)
{
row.push_back(0);
}
//push back empty rows
for(int j = 0; j < node_num; j++)
{
edges.push_back(row);
}
}
Example data file (provided by professor):
A
B
C
D
A B 3
A C 10
A D 12
B C 1
B D 14
C D 4
I know this code is somewhat sloppy as it is just the beginning of my project, but I always tend to get caught up on every bug I encounter until I can fix it. And I have never seen anything like this so I appreciate yall's time and help!