New to fstream and ofstream

This is a discussion on New to fstream and ofstream within the C++ Programming forums, part of the General Programming Boards category; I've just learned how to use write to files and output whats in them off of this site's tutorial and ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    >> stops on the first white space
    read about getline() function
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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 04:16 AM.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,338
    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, 11:21 AM
  4. Why won't fstream file open?
    By Brown Drake in forum C++ Programming
    Replies: 4
    Last Post: 11-20-2001, 10:30 AM
  5. Fstream Problem
    By Xterria in forum C++ Programming
    Replies: 2
    Last Post: 08-25-2001, 11:03 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21