gpt4 book ai didi

c++ - cout 不起作用时如何检测无限循环?

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:20 38 4
gpt4 key购买 nike

我用 C++ 实现了 Edmonds–Karp 算法,当我用一个小图对其进行测试时,它没有完成,但我无法确定它卡在哪里。我通常将 cout 与某些东西一起使用,直到找到它无限打印的位置,但我没有在这里工作。该程序从不打印任何东西。我试图将 cout 作为程序的第一行,但它没有打印出来。任何人都知道为什么它从不打印任何东西和/或有一些提示我如何识别无限循环?

代码,如果有人想看,是:

int main ()
{
FILE *graph_file;
graph_file = fopen("grafo.txt", "r");
if (graph_file == NULL)
{
cout << "Não foi possível abrir o arquivo 'grafo.txt'" << endl;
exit(1);
}

char line[MAX_LINE];
char *line_split = NULL;

// pegar informações do grafo para armazenar o tamanho adequado dos vetores
fgets(line, MAX_LINE, graph_file);
while (feof(graph_file) == 0)
{
if (line[0] == 'a') // é uma aresta
{
line_split = strtok(line, " "); // a

line_split = strtok(NULL, " "); // vertice origem da aresta
int origin = atoi(line_split);

line_split = strtok(NULL, " "); // vertice destino da aresta
int destiny = atoi(line_split);

line_split = strtok(NULL, " "); // peso da atesta
int capacity = atoi(line_split);

insert_edge(origin, destiny, capacity);
}
fgets(line, MAX_LINE, graph_file);
}

//print_graph();

int origin = 1;
int destiny = 6;

calc_valid_path(origin, destiny);

while (precursor[destiny] != 0)
{
int max_cap = get_path_max_cap(origin, destiny);

int i = destiny;
while (i != origin)
{
Edge *temp = get_edge(precursor[i], i);
temp->flow = temp->flow + max_cap;

temp = get_edge(i, precursor[i]);
if (temp == NULL) // se a aresta inversa ainda não existe, cria
{
insert_edge (i, precursor[i], 0);
temp = get_edge(i, precursor[i]);
}
temp->flow = temp->flow - max_cap;
i = precursor[i];
}

calc_valid_path(origin, destiny);
}

cout << "Flow: " << get_flow(destiny);

return 0;
}

最佳答案

听起来好像输出没有被刷新:std::cout 默认情况下是缓冲的,听起来好像缓冲区没有被填满。快速解决此问题的最简单方法是将流设置为始终刷新:

std::cout << std::unitbuf;

通常 std::cerr 用于调试,而不是将此流作为默认设置的 std::ios_base::unitbuf。或者,您可以显式刷新流:

std::cout << std::flush;

虽然我没有看过你的算法。

关于c++ - cout 不起作用时如何检测无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18624129/

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