Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Why don't files work (c++)?

+3 votes
asked Dec 30, 2022 by Traian Danciu (150 points)
#include <fstream>

using namespace std;

ifstream fin("file.in");

ofstream fout("file.out");

int main()

{

int a,b;

fin>>a>>b;

fout<<a+b;

return 0;

}

The code just doesn't run, why is that?

2 Answers

+1 vote
answered Jan 1 by Peter Minarik (66,990 points)

The code works fine, you just have to have file.in file in your project (alongside the main.cpp) that has two numbers separated by white space

commented Jan 2 by Traian Mihai Danciu (100 points)
Yeah, but it opens the console instead. Why?
commented Jan 3 by Peter Minarik (66,990 points)
I'm not sure what you mean.

It opens the file.in, reads the values from it. Then it writes the correct output into the file.out.

Online GDB may put some message on the console to indicate the program has executed correctly and without any issues.
commented Jan 3 by Traian Mihai Danciu (100 points)
I mean, there are some kind of bugs, sometimes it works, sometimes not. It's just that it does not write the correct output in file.out. If I use it with the console, it is perfectly fine.
0 votes
answered Jan 5 by Max Jian (690 points)
I would recommend just using freopen - example: freopen("testf.in", "r", stdin). Changing the ‘r’ to ‘w’ will turn it from reading to writing. Then you can just use cin and cout and it will automatically change it to the files.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...