Invalid initalization

Hey what's up, I'm back with more problems. This morning I was trying to make a program that outputs all the ASCII characters to a textfile, then outputs that same information to the console.

My text file is not showing any ascii characters, it's just showing the initial numbers but that's not really what I'm interested in. I'm interested in knowing why when I try to pass cout to my function do I get the error "Invalid initialization of non-const reference of type 'std::ofstream&' from expression..."

This is my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
void text_writer(ofstream & os);


int main()
{
    ofstream fout;
    const char * fn = "ascii.txt";
    fout.open(fn);
    if (!fout.is_open())
    {
        cout << "Can't open " << fn << "\nBye!.";
        exit(EXIT_FAILURE);
    }
    else
        text_writer(fout);
    fout.close();

    text_writer(cout); // this line gives me the error


    return 0;
}

void text_writer(ofstream & os)
{
    os << "Writing to this file all ASCII characters\n\n";
    for (int i = 0; i < 127; i++)
    {
        os.width(12);
        os << "ch = " << i;
        os.width(15);
        cout.put(i);
        os << endl;
    }
}


Thanks for any help you can offer!
Last edited on
I'm interested in knowing why when I try to pass cout to my function do I get the error "Invalid initialization of non-const reference of type 'std::ofstream&' from expression..."


std::cout is an object of type std::ostream (see: http://cplusplus.com/reference/iostream/cout/).
You're passing it to a function that expects a std::ofstream (line 22).
But std::ofstream is a subclass of std::ostream, so it doesn't work. Remember that all polar bears are bears but not all bears are polar bears ;)
Change the parameter type to std::ostream& - that'll fix your first problem.

Also on line 36, why are you calling put() on cout? Why not os?

Regards, keineahnung
Haha thank you . I just noticed the cout.put thing, i have no idea. I'm so used to working with cout :P I'll change that as well, thank you!
Topic archived. No new replies allowed.