Thread: Reading multiple data types to file

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    13

    Reading multiple data types to file

    If got a problem for reading multiple data types to a file using operator>> and getline.

    Let say I've got the following code:
    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    
    int main()
    {
    	ofstream fout("testfile.txt");
    	string s = "Writing multiple data types to a file", t, u;
    	fout << s << '\n';
    	int i = 2, j;
    	fout << i << '\n';
    	fout << s << '\n';
    	fout.close();
    	
    	ifstream fin("testfile.txt");
    	getline(fin, t);
    	fin >> j;
    	getline(fin, u);
    	cout << t << endl << j << endl << u << endl;
    	
    	return 0;
    }
    The problem is that string u is emtpy and not the the content of s that it supposed to have.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    fin >> j; does NOT consume a newline, so it instead gets read by the following getline.

    Either
    - don't mix input methods (like cin and getline)
    - use cin.ignore() to skip unused (and unwanted) data.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    13
    Thanks for the information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  2. reading data into a queue from file
    By bcianfrocca in forum C++ Programming
    Replies: 12
    Last Post: 11-17-2005, 11:28 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. help with reading a data file
    By zipfur in forum C Programming
    Replies: 4
    Last Post: 11-02-2002, 06:50 PM
  5. Help reading data file...
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 02-25-2002, 12:49 PM