Hi all,
I have written this piece of code: it is supposed to recieve an istream with a string which is used to create a graph.
the istream is of the follwing format:
|vertex1,vertex2, .. ,vertexn|(v1->v2),(vi->vj)..|
example:
|1,2,3|(1->2),(2->3)|
will create a graph, where 1,2,3 are vertices, and there are edges 1->2 and 2->3
however this code fails: it creates the vertices, assigns the right "source" for the edge, but put gibrish into "dest"
below is the code, I have marked the problematic line
Please help!!
Code:
istream& operator >> (istream& in,Graph & g1)
{
//local variables
char string[MAX];
char buff;
int curr=0,temp,source,dest;
Vertex v1;
stringstream ss;
/**************GET VERTECIES FROM STREAM**************************************/
//get rid of first '|'
in >> (in, buff);
//get first num
in >> (in, buff);
while (buff!='|')
{
//while still reading digits (not comma)
while (isdigit(buff))
{
string[curr]=buff;
in >>(in, buff);
curr++;
}
//have now read comma or |(is value of buff)
//set ss to empty string stream
ss.str(string);
//convert to integer
ss >> temp;
//add new vertex with value
g1.addVer(temp);
//set pos in string to 0
curr=0;
string[curr]='\0';
//read next digit
if (buff!='|')
in >>(in, buff);
}
/*********************GET EDGES FROM STREAM***********************************/
//get first "("
in >> (in, buff);
while (buff!='|')
{
//for each edge!!!!!
//flush stream
ss.str("");
/********* GET SOURCE*************************/
in >> (in, buff);
while (isdigit(buff))
{
string[curr]=buff;
in >>(in, buff);
curr++;
}
//add source to int
string[curr]='\0';
ss.flush();
ss.str(string);
ss >> source;
/*********FLUSH "->" ***************************/
in >> (in, buff) >> (in, buff);
//at this stage, buff contains first dig of dest vertex
curr=0;
while (isdigit(buff))
{
string[curr]=buff;
in >>(in, buff);
curr++;
}
//add dest to int
string[curr]='\0';
ss.flush();
ss.str(string);
ss >> dest; //HERE"S THE PROBLEM: DOESNT ASSIGN
g1.addEd(source,dest);
//at this stage buff contains the final ) of edge
//get char after bracket (comma or |)
in >> (in, buff);
if (buff == ',')
in >> (in, buff) >> (in,buff);
}
return in;
}