0

I'm using Mac OS X (El Captain) and CLion and I've created a project that contains the following files:

1) main.cpp:

#include <fstream>
std::ifstream cin("/Users/alekscooper/Dropbox/96 - CLion Dummy Project/input.txt");
std::ofstream cout("/Users/alekscooper/Dropbox/96 - CLion Dummy Project/output.txt");

#include "foo.h"

using std::endl;

int main() {
    int x, y, z;
    cin >> x >> y >> z;
    cout << x + y + z << " Test sum is printed" << endl;
    foo();
    return 0;
}

2) foo.h

void foo();

3) one_more_file.cpp

#pragma once

#include <iostream>

void foo() {
    std::cout << "I'm a foo" << std::endl;
}

What I expect my project:

  • to contain multiple *.cpp and *.h files
  • to print from all the functions in all the files into .../output.txt

What the problem is:

While the cout in the main.cpp does print the test sum and the message in .../output.txt, the cout in the foo() function prints 'I'm a foo' into the console window. In other words, the input in the foo() function does not get redirected into .../output.txt. Why is that and how can I fix that?

alekscooper
  • 795
  • 1
  • 7
  • 19
  • This is not a question about how to redirect cout in general, this is a question about how to redirect cout if it is in another file in a multiple source file project, it's a question about an unexpected behavior of code, not a 'do it for me I'm too lazy' question. – alekscooper Feb 20 '18 at 14:25
  • 1
    Your `cout` in main and `std::cout` in foo are two totally different streams. They just have similar names. To be more flexible about where the output goes you could have `void foo(std::ostream& output)` and use `output <<` for all output. Then the caller of foo can decide where the output goes by passing a suitable stream. – Bo Persson Feb 20 '18 at 14:35

0 Answers0