file handling example not working

Sep 12, 2009 at 2:15pm
I got this code out of "The Complete Idiot's Guide to C++". I'm on chapter 18, which is about file handling. bAll the other code in the book needed slight modification (adding "using namespace std") in order to get it to work with my compiler (I use Bloodshed Dev-C++). This program, however I cannot get to work. Can you help me? Like I said, this was taken directly from the book. The only thing I modified was adding "using namespace std".

--CODE--
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char ch;
char filename[20]="c:test.txt";
int mode=ios::out;
fstream fout( filename, ios::mode ); /*The problem is this line. It says "invalid file conversion from 'int' to 'std::_Ios_Openmode' */
cout << "Ready for input; Use [CTRL] + z to end." << endl;
while(cin.get(ch))
{
fout.put(ch);
}
fout.close();
system("PAUSE");
return(0);
}
--CODE--
Sep 12, 2009 at 2:46pm
Change the line to:
fstream fout(filename, ios::out);

It is meant as a placeholder for ios::in or ios::out and whether you are opening in binary mode or not:
ios::in | binary or ios::out | binary.

Of course, if you used an ofstream or an ifstream (output or input only) you could omit the opening mode completely.
Sep 12, 2009 at 2:52pm
Thank you Chewbob! That does make it work!

Could you give me an example of using an ofstream or an ifstream?
Sep 12, 2009 at 3:05pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    char ch;
    char filename[20]="c:test.txt";
    ofstream fout(filename);
    cout << "Ready for input; Use [CTRL] + z to end." << endl;
    while(cin.get(ch))
    {
        fout.put(ch);
    }
    fout.close();

    return 0;
}


That is pretty much the same as your program above. The difference is that fstream can be used for both input and output, where as ofstream and ifstream and only be used for output and input respectively.

I also just noticed the line int mode = ios::out; in your code. If you had put:
fstream fout(filename, mode);
That would have also worked.
Last edited on Sep 12, 2009 at 3:08pm
Sep 15, 2009 at 9:37pm
That was the problem though. "fstream fout (filename, mode)" didn't work with my Bloodshed dev-C++ compiler.

BTW, how do u post ur code into formatted code like that?
Sep 15, 2009 at 10:37pm
Enclose your code inside code tags. [co de] [/code] without the space.

Also, in your first post you your line said fstream fout(filename, ios::mode); rather than fstream fout(filename, mode);, so are you sure that's not your problem?

If that doesn't work, try changing the line int mode = ios::out; to
ios_base::openmode mode = ios::out;.
Last edited on Sep 15, 2009 at 10:38pm
Topic archived. No new replies allowed.