gpt4 book ai didi

c++ - 读取输入文件时无限循环?

转载 作者:行者123 更新时间:2023-11-30 02:50:12 93 4
gpt4 key购买 nike

我在代码中得到一个无限循环while(input.find(' ', pos1) != string::npos)我创建这段代码只是为了通过重定向读取输入并创建图的顶点图和字符 vector 。它不是很优雅,所以如果您想建议一种更有效的阅读输入方式,那也很好。谢谢!

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

输入

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

最佳答案

问题是:

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条件。

关于c++ - 读取输入文件时无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20622338/

93 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com