简体   繁体   English

读入输入文件时无限循环?

[英]Infinite loop when reading in input file?

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. 我在代码中获得了一个无限循环while(input.find(' ', pos1) != string::npos)我创建此代码只是为了通过重定向读入输入并创建一个顶点映射和一个字符向量图表。 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

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; 改变pos1 = pos2; to pos1 = pos2+1; pos1 = pos2+1; -- it never moves, so the while loop never ends. - 它永远不会移动,所以while循环永远不会结束。

You also need to make sure pos1 < string::length in your while condition. 您还需要在while条件下确保pos1 < string::length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM