I'm writing a console app to ask the users for the edges of a graph and compute the MST for the give nodes but am having trouble parsing the input. The data is give in the form:
(node1,node2) weight
and the following code will extract the 2 nodes but I constantly get an out_of_range exception when trying to get the get the weight.
Code:
int main() {
string cmd;
int startIdx, endIdx, length;
int vert1, vert2, weight;
// command loop, ends with EOF
cout << ": ";
while(true) {
cin >> cmd;
// terminate on EOF
if(cin.eof() != 0) {
cout << endl;
return 0;
}
// parse input
length = cmd.capacity() - 1;
startIdx = cmd.find('(', 0);
endIdx = cmd.find(',', startIdx);
vert1 = atoi((cmd.substr(startIdx + 1, endIdx - startIdx - 1)).c_str());
startIdx = endIdx;
endIdx = cmd.find(')', startIdx);
vert2 = atoi((cmd.substr(startIdx + 1, endIdx - startIdx - 1)).c_str());
startIdx = endIdx + 1;
endIdx = length;
weight = atoi((cmd.substr(startIdx + 1, endIdx - startIdx)).c_str());
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "From: " << vert1 << " To: " << vert2 << " Weight: " << weight << endl;
cout << ": ";
}
return 0;
}
Everything I've read says I can call substr() with the start index alone and it will return a string from the index to the end of the string but that gives me the same exception. I've tried with a length of 1 when I provide a 4-digit weight (so I know I'm not running past the end of the string) and still get the same exception.
Could someone please explain what I'm not getting about substr()?
Thanks.
Jasen