I have my own little graph class and I want to create a graph by reading in a file, containing the necessary information like number of vertices, edges, etc. The files are in the STP format. The code works fine, if I just read in the file word by word.
Now I need to identify certain keywords like "Nodes", followed by the number of vertices. When reaching such a keyword, I read in the next word which I then store as the number of vertices. This results in a segmentation fault
Here's the code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "graph2.h"
Graph readin(char const * filename) {
Graph mygraph(0);
std::ifstream file (filename);
if (not file) throw std::runtime_error("Couldn't open file.");
std::string line, word;
int head, tail;
// magic password
std::getline(file,line);
if (line == "33D32945 STP File, STP Format Version 1.0") {
while (file >> word) {
if (word == "Nodes") {
file >> mygraph.numvertices;
}
else if (word == "E") {
file >> tail;
file >> head;
mygraph.edge(tail,head,Graph::add);
}
else if (word == "EOF") break;
}
}
else throw std::runtime_error("File is not in STP file format.");
return mygraph;
}
int main(int argc, char* argv[]) {
if (argc > 1) {
Graph mygraph = readin(argv[1]);
mygraph.print();
}
return 0;
}
It works fine like that:
if (line == "33D32945 STP File, STP Format Version 1.0") {
while (file >> word) {
std::cout << word << std::endl;
}
}
Anybody got any idea?