File reading and writing problem

I'm doing a very basic program in C++, after 2 years of python experience. I do not, however, understand why my code does not work. I have tested it out for ages, and even used the code that the website I have been learning off provided for us, which didn't work for me. This is using linux (kubuntu), using the g++ compiler. The test script (sh file, basically command) I use to run the file is

1
2
g++ main.cpp -o output
./output

It produces all kinds of wierd things in the file "output". It looks like the first number is always 0, and the second seems to be a randomly generated one in the range of int.
In the end, test.out does not exist at all. It produces no errors and runs up to the line before the output to the file, so it seems like it runs that line but the line doesn't do what it should be doing. I suspect it may be a problem with the OS, as there seems to be nothing wrong with the code. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream fin ("test.in");
    ofstream fout ("test.out");

    int num1, num2, tot;
    fin >> num1 >> num2;
    tot = num1 + num2;
    cout << num1 << "\n" << num2 << "\n" << tot << "\n";

    fout << tot << endl;
    return 0;
}
Can you show us the contents of test.in?
I think you have to open the file with fin.open() to write / read it
No, you don't; his code has the constructor open the file. You shouldn't open a file twice...
Topic archived. No new replies allowed.