2013-12-16 104 views
1

我在代碼中獲得了無限循環while(input.find(' ', pos1) != string::npos)我創建此代碼只是爲了通過重定向讀取輸入併爲圖形創建頂點和字符矢量的映射。這不是很優雅,所以如果你想建議一個更有效的方式來閱讀輸入,那也是很好的。謝謝!在輸入文件中讀取時無限循環?

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("")) 
    { 

     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]]); 
} 

輸入

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 

回答

3

這裏的問題:

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; 
    }; 

變化pos1 = pos2;pos1 = pos2+1; - 不會變化,所以while循環永遠不會結束。

您還需要確保pos1 < string::length在您的while條件。

+0

增加了另一點。 –

相關問題