Ofstream and Ifstream

This is a discussion on Ofstream and Ifstream within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> #include <fstream> using namespace std; typedef string str; void main() { char wrd[50]; ofstream fout("shorttext.txt"); fout << ...

  1. #1
    Perverted unanimous's Avatar
    Join Date
    Oct 2001
    Posts
    336

    Question Ofstream and Ifstream

    Code:
    #include <iostream>
    
    #include <fstream>
    
    using namespace std;
    typedef string str;
    void main()
    {
      char wrd[50];
    
    
    
      ofstream fout("shorttext.txt");
    
      fout << "Hello World";
     
      fout.close();
      
      
      ifstream fin("shorttext.txt");
    
      fin >> wrd;
    
      cout << wrd;
      fin.close();
    }
    In the above code when run it will print the text to a file but will only read one word how would I have it read the whole line.
    Give me a bad reputation!!!

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    194
    fin.getline(wrd,49,'\n');

    The 49 is the max number of characters to get, and the \n is the char to stop at. So this line will read in 49 chars or a whole line, which ever is smaller
    you have to leave room for the null terminator, which is why you have to take 1 away from the array size

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ofstream... broke as a result of ifstream fix
    By tms43 in forum C++ Programming
    Replies: 3
    Last Post: 11-12-2006, 11:40 AM
  2. ofstream and ifstream for searching and writing
    By johnnyd in forum C++ Programming
    Replies: 6
    Last Post: 03-17-2003, 08:34 AM
  3. ifstream and ofstream
    By Stan100 in forum C++ Programming
    Replies: 2
    Last Post: 11-11-2002, 04:53 PM
  4. Replies: 9
    Last Post: 06-06-2002, 08:03 PM
  5. STL to: Cin, Cout, ifstream & ofstream
    By kuphryn in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2001, 09:32 AM

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