Problem with <fstream>

Hi guys,

Hopefully someone can help me here. I have been working through the book "C++ programming in easy steps" using code::blocks and have come to the writing a file segment. After writing the code and trying to run it I do not get the desired output just a blank console with a return 0 and press a key to continue. I can get the desired output if I replace

writer << poem << endl ; with
cout << poem << endl ;

But this defeats the object, I have no idea what the problem is and my code is the same as the example code provided.

Thanks guys.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <string>
#include <iostream>
using namespace std ;

int main()
{
  string poem = "\n\tI never saw a man who looked" ;
  poem.append( "\n\tWith such a wistful eye" ) ;
  poem.append( "\n\tUpon that little tent of blue" ) ;
  poem.append( "\n\tWhich prisoners call the sky" ) ;


  ofstream writer( "poem.txt") ;

  if(! writer)
  {
      cout << "Error opening file for output" << endl ;
      return -1 ;
  }

  writer << poem << endl ;
  writer.close() ;
This program writes to a file named poem.txt, it does not write anything to the screen unless it can not open the file to write.

Look inside the file poem.txt
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
#include <fstream>
#include <string>
#include <iostream>
#include <conio.h>

using namespace std ;

int main()
{
  string poem = "\n\tI never saw a man who looked" ;
  poem.append( "\n\tWith such a wistful eye" ) ;
  poem.append( "\n\tUpon that little tent of blue" ) ;
  poem.append( "\n\tWhich prisoners call the sky" ) ;


  ofstream writer( "poem.txt") ;

  if(! writer)
  {
      cout << "Error opening file for output" << endl ;
      return -1 ;
  }

  ifstream writer("poem.txt");
    if(!writer) {
		cout << "Cannot find file.\n";
		return 1;
}

  writer << poem << endl ;
  writer.close() ;

getch();
return 0;
}

Hope this helps.
Last edited on
Thanks the help there guys, I did not realize it wasn't supposed to appear onscreen at all. It did not make that clear to me in the book.
Topic archived. No new replies allowed.