C++ 读取输入文件时的无限循环?

C++ 读取输入文件时的无限循环?,c++,C++,我在代码中得到一个无限循环while(input.find(“”,pos1)!=string::npos)我创建此代码只是为了通过重定向读取输入,并为图形创建顶点映射和字符向量。它不是很优雅,所以如果你想在输入中提出一种更有效的阅读方法,那也很好。谢谢 void MSTapp::processFile() { int pos1; int pos2; map<char, Vertex*> adjacencyList; vector<char> listOrder; stri

我在代码中得到一个无限循环
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("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]]);
}
问题是:

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
循环永远不会结束

您还需要确保
while
条件中的
pos1

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