【问题标题】:C++ - my program stops running `freopen` function from <cstdio>C++ - 我的程序停止从 <cstdio> 运行 `freopen` 函数
【发布时间】:2022-12-09 00:16:28
【问题描述】:

在我的main.cpp


#include <cstdio>
#include "hashtable.h"

int main() {
    printf("1hello");
    freopen("2.txt", "w", stdout);
    printf("2hello");
    freopen("1.txt", "r", stdin);
    printf("3hello");
    int type;
    char buffer[1000];int data;
    hashtable table(10000, new naive_hashing(), new linear_probe());
    while (true) {
        scanf("%d", &type);
        if (type == 0) {
            scanf("%s", buffer);scanf("%d", &data);
            table.insert(hash_entry(buffer, data));
        }
        else if (type == 1) {
            scanf("%s", buffer);
            printf("%d\n", table.query(buffer));
        }
        else break;
    }
    return 0;
}

1.txt:

0 dhu_try 3039
0 shirin 3024
0 SiamakDeCode 2647
0 huanghansheng 233
1 dhu
1 dhu_try
1 shirin
1 siamakdecode0
1 huanghansheng
2

output:

1hello

如您所见,程序在进入第一个 freopen 函数后暂停了。我已经检查了文档,但仍然找不到它停止运行的原因。谁能帮帮我吗? :恳求脸:

【问题讨论】:

  • 知道freopen()的人可能会出现,但为什么不使用&lt;fstream&gt;呢?或者&lt;iostream&gt; 就此而言?我根本不相信这是一个 C++ 问题/程序。
  • 执行程序后,您在2.txt 中看到了什么?我希望 freopen("2.txt", "w", stdout); 之后的所有 printf 输出都在该文件中。
  • 我很好奇:作为学习 C++ 的一部分,您究竟是如何知道 freopenscanf 的?上次类似的事情是这里的主题,它被确定为坏知识的来源是一个不称职的 C++ 讲师。你在同一条船上吗?

标签: c++ debugging freopen cstdio


【解决方案1】:

当你这样做时,你将所有输出重定向到 stdout 到文件 2.txt

reopen("2.txt", "w", stdout);

这就是为什么在 freopen 之后控制台上没有显示 printf 输出。查看文件 2.txt,您很可能会在那里看到输出 - 如果 freopen 成功。始终检查可能失败的功能是否已成功。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2016-03-29
    • 2016-01-16
    • 1970-01-01
    • 2018-04-12
    • 2018-10-18
    相关资源
    最近更新 更多