Sean
Sean

Reputation: 51

How to view the output of c++ program which compiled on terminal

#include<iostream>
using namespace std;

int main()
{
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);

    int a,b;
    cin >> a >> b;
    cout << a+b;    
    return 0;
}

When I compile it from terminal(Mac), it is not read meaning from input.txt and do not write to output.txt. What is the problem?

Upvotes: 1

Views: 3194

Answers (2)

user2784234
user2784234

Reputation: 451

@Chingy, I saw your screenshot. Please look at this documentation for basic introduction to g++. Please note that the compilation and execution of a program are different instances.

First step is compilation, which you are doing correctly as per the screenshot.
1) g++ 1.cpp.

This step will create an executable (a.out) which you need to run separately in order to get the desired behavior from your program.

Please execute the program as follows:
2) ./a.out

Upvotes: 1

Vishnu Kanwar
Vishnu Kanwar

Reputation: 781

You forget to close files gracefully

fclose (stdin);
fclose (stdout);

Note: The fclose() function flushes the stream pointed to by stdout (writing any buffered output data using fflush and closes the underlying file descriptor.

Upvotes: 0

Related Questions