3

I'm new to Visual Studio Code, I've managed to set up the debugger with mingw but reading from files doesn't work. While running the executable it reads correctly from the file and displays the correct answer but when debugging it always displays 0.

#include <iostream>
#include <fstream>

using namespace std;
ifstream f("data.in");

int main()
{
    int n;
    f>>n;
    cout<<n;
}
  • 2
    you should check if the file could be opnened – 463035818_is_not_an_ai Nov 25 '20 at 19:01
  • Thank you! I'll try to do that but I still don't understand why it works when I run the exe but not while debugging – sobo sapiens Nov 25 '20 at 19:04
  • 6
    Maybe the working directory is different when debugging versus clicking on the file. Related: [https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debug](https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debug) – drescherjm Nov 25 '20 at 19:04
  • Likeliest reason is that your program tries to find `data.in` in a different place from where you put it. – john Nov 25 '20 at 19:04
  • 4
    And this is why you should *never* open files using relative paths, *always* use absolute paths. If you need to open a file that is relative to the EXE (or any specific folder), get the EXE/folder's absolute path first, then apply the relative path to it to make a new absolute path, then use that new path to open the file. – Remy Lebeau Nov 25 '20 at 19:07
  • Yes you are right, as I said I'm a newbie so I didn't even know I had to modify the launch.json Thank you all so much! – sobo sapiens Nov 25 '20 at 19:09
  • 1
    I would move `ifstream f("data.in");` into your `int main()` and check and return an error message if the file could not be opened. – drescherjm Nov 25 '20 at 19:10

0 Answers0