当 COUT 不起作用时,如何检测无限循环?

how can I detect infinite loop when cout doesn't work?

本文关键字:检测 无限循环 何检测 不起作用 COUT      更新时间:2023-10-16

我在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;

不过,我没有看过你的算法。