Thread: getline() and file I/O

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663

    getline() and file I/O

    I can't figure out a problem I'm having. The input file looks like this:

    input.txt:
    david5555555555555555
    sally6666666666666666666666

    and I'm trying to use getline() to pick out just the name from each line, and then use ignore() to discard the rest of the line, but my output file ends up looking like this:

    output.txt:
    david

    instead of:

    output.txt:
    david
    sally

    Here is the code:
    Code:
    #include <fstream>
    #include <iostream>
    using namespace std;
    
    int main()
    { 
    	char text[6];
    	char word[6];
    	ifstream inFile("C:\\TestData\\input.txt");
    	ofstream outFile("C:\\TestData\\output.txt");
    	
    	inFile.getline(text, 6);
    	cout<<"tellg(): "<<inFile.tellg()<<endl;
    	//I get tellg()=-1 here???
    	
    	inFile.ignore(1000, '\n');
    	//I thought the get pointer would be 6 here
    	//so I'm trying to discard the rest of the 
    	//char's on the first line up to an including
    	//the '\n' to set up for reading the next line 
    	//of data.
    	
    	inFile.getline(word, 6);
    	
    	outFile<<text;
    	outFile<<word;
    
    	return 0;
    }
    I also tried the same thing creating a dummy variable:

    char overflow[200];

    and doing this:

    inFile.getline(text, 6);
    inFile.geline(overflow, 200);
    inFile.getline(word, 6);

    but I got the same output. I thought with this statement:

    inFile.getline(text, 6);

    getline() was supposed to stop reading from the stream after 5 char's or until a '\n' (the default delimiter) was encountered, and therefore I needed to do something to remove the rest of the char's from the line, but it's not working the way I exepected.
    Last edited by 7stud; 04-30-2003 at 03:37 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help needed with file I/O
    By vishalbhingarka in forum C++ Programming
    Replies: 17
    Last Post: 11-30-2005, 11:20 AM
  2. Help with getline() and file reading
    By evilkillerfiggi in forum C++ Programming
    Replies: 5
    Last Post: 10-15-2005, 03:49 PM
  3. getline function to read 1 line from a text file
    By kes103 in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2004, 06:21 PM
  4. problem with getline() file I/O
    By hyperion in forum C++ Programming
    Replies: 4
    Last Post: 12-08-2003, 09:34 AM
  5. getline i/o
    By kylesbigdog in forum C++ Programming
    Replies: 8
    Last Post: 04-23-2003, 08:25 AM