Not getting output using freopen in c++ :-vs code showing

627 Views Asked by At
#include <iostream>
using namespace std;
int main() {
#ifdef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int n;
    cin >> n;
    cout << n + 1;
    return 0;
}

while using freopen for input and output result of my program in c++ in vs code i am not getting ouput in ouput.txt file.for eg:i created a program to enter a no. n and ouput n+1. But while entering 24 in input i am geting 32765 in ouput.txt but in my terminal i am getting 25 that's it.and by compiling the program again and again 32765 changes to 32767 and so on.

1

There are 1 best solutions below

0
On

When reading files this way, make sure the file you are referring to is in the present working directory of the terminal.


In the following folder structure

ParentFolder
├── Folder1
│   ├── code
│   ├── code.cpp
│   └── input.txt
└── Folder2
    └── input.txt

If your present working directory is Folder2, then input file used will be ParentFolder/Folder2/input.txt even if you have an input file in the same folder as your code and executable, as relative paths are decided using terminals working directory.

And naturally, if the file doesn't exist/can't be opened, you will get grabage numbers.