Thread: Ofstream and Ifstream

  1. #1

    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.

  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, 07: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