1

I get an infinite loop in the code while(input.find(' ', pos1) != string::npos)I created this code simply to read in the input via redirection and create a map of vertexes and a vector of characters for a graph. It's not very elegant so if you want to suggest a more effective way of reading in the input then that's good too. Thanks!

void MSTapp::processFile() { int pos1; int pos2; map<char, Vertex*> adjacencyList; vector<char> listOrder; string input; bool test = false; while (getline(cin, input)) { pos1 = pos2 = 0; if(std::string::npos != input.find_first_of("0123456789")) { char source = input[0]; char destination = input[2]; stringstream ss(input.substr(4)); int weight; ss >> weight; Edge newEdge(destination, weight); adjacencyList[source]->addEdge(destination, newEdge); Edge roadBack(source, weight); adjacencyList[destination]->addEdge(source, roadBack); } else { while(input.find(' ', pos1) != string::npos) { pos2 = input.find(' ', pos1); char vertex = input[pos1]; listOrder.push_back(vertex); Vertex* newVertex = new Vertex(vertex); adjacencyList.insert(make_pair(vertex, newVertex)); pos1 = pos2 + 1; }; }; }; Graph graph(listOrder, adjacencyList); prim(graph, adjacencyList[listOrder[0]]); } 

Input

A B C D E F G A B 3 A E 4 B C 7 B E 6 B F 5 C D 9 C F 8 D F 9 D G 4 E F 6 F G 8 

1 Answer 1

3

Here's the problem:

while(input.find(' ', pos1) != string::npos) { pos2 = input.find(' ', pos1); char vertex = input[pos1]; listOrder.push_back(vertex); Vertex* newVertex = new Vertex(vertex); adjacencyList.insert(make_pair(vertex, newVertex)); pos1 = pos2; }; 

Change pos1 = pos2; to pos1 = pos2+1; -- it never moves, so the while loop never ends.

You also need to make sure pos1 < string::length in your while condition.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.