Thread: New to fstream and ofstream

  1. #1
    Sanity is for the weak! beene's Avatar
    Join Date
    Jul 2006
    Posts
    321

    New to fstream and ofstream

    I've just learned how to use write to files and output whats in them off of this site's tutorial and was wondering how to output the whole string of characters into the console window:

    Code:
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        char str[10];
        
        /*creates an instance of ofstream and opens example.txt*/
        ofstream a_file ( "example.txt" );
        /*outputs to example.txt through a_file*/
        a_file << "This is my first program using files!!!";
        /*close the file stream explicitly*/
        a_file.close();
        /*opens the file for reading*/
        ifstream b_file ( "example.txt" );
        /*reads the string from the file*/
        b_file >> str;
        /*should print this*/
        cout << str << endl;
        cin.get();
    }
    This program only outputs "this".

    Thanks for the help in advance!

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    >> stops on the first white space
    read about getline() function
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Sanity is for the weak! beene's Avatar
    Join Date
    Jul 2006
    Posts
    321
    Yes, thank you, that works
    Last edited by beene; 01-22-2007 at 05:16 AM.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Even if this site's tutorials teach C-style strings, I would be learning C++ strings and converting the code to use them instead. In this case it would mean a slightly different version of getline, and it would allow you to output more than "This is m".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to use fstream library
    By salmanriaz in forum C++ Programming
    Replies: 7
    Last Post: 03-12-2009, 07:06 AM
  2. Using fstream
    By Sridar in forum C++ Programming
    Replies: 5
    Last Post: 06-30-2005, 12:36 PM
  3. Are fstream and ofstream incompatible?
    By johnnyd in forum C++ Programming
    Replies: 5
    Last Post: 03-19-2003, 12:21 PM
  4. Why won't fstream file open?
    By Brown Drake in forum C++ Programming
    Replies: 4
    Last Post: 11-20-2001, 11:30 AM
  5. Fstream Problem
    By Xterria in forum C++ Programming
    Replies: 2
    Last Post: 08-25-2001, 11:03 PM