-1

In my 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

As you can see the program paused after it entered the first freopen function. I have checked the document already and still yet cannot find the reason why it stopped running. Can anyone help me please? :pleading_face:

  • Someone who knows `freopen()` will likely come along, but why not use [``](https://en.cppreference.com/w/cpp/header/fstream)? Or [``](https://en.cppreference.com/w/cpp/header/istream) for that matter? I'm not convinced that this is a C++ question/program at all. – sweenish Dec 08 '22 at 15:51
  • 2
    What do you see in `2.txt` after you've executed the program? I would expect all the `printf` outputs after `freopen("2.txt", "w", stdout);` to be in that file. – Ted Lyngmo Dec 08 '22 at 15:52
  • I'm curious: as part of learning C++, how exactly did you become aware of `freopen` and `scanf`? Last time something similar was the subject matter here it was determined that the source of bad knowledge was an incompetent C++ instructor. Are you in the same boat? – Sam Varshavchik Dec 08 '22 at 15:57

1 Answers1

1

You redirected all output to stdout to the file 2.txt when you did

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

That's why no printf outputs are shown on the console after that freopen. Look in the file 2.txt and you will most probably see the output there - if the freopen succeeded. Always check if functions that can fail have succeeded.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108