Thread: getline function to read 1 line from a text file

  1. #1
    Registered User
    Join Date
    Dec 2001

    getline function to read 1 line from a text file

    I've search the other threads and although I couldn't find or haven't yet found the specific answer it appears that the getline function could be used to read one whole line of a text file.
    Could/would someone please explain how to use getline (instead of scanf because it stops at the first white space when using "%s" format specifier) to read in one line of string text from a text file.

    thanks in advance

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003

  3. #3
    Registered User
    Join Date
    Dec 2001
    Thank you code plug, but I was looking for some specific information on how to read a whole line from a text file.
    The FAQ reference doesn't even have the word file in it.

  4. #4
    Registered User
    Join Date
    Mar 2002
    anything you can do with cin you can do with a stream to read files---ifstream or fstream in ios::in mode.

    //Version 1
    ifstream fin("myfile.txt");
    std::string myString;
    getline(fin, myString);
    version 2
    fstream fin("myfile.txt", ios::in);
    char myString[256];
    fin.getline(myString, 255);

    in both versions the third parameter of getline defaults to the new line char such that everything up to the first newline char in Version 1 (at least til you run out of memory) and everything up to the first newline char or until 255 char have been read in in Version 2. This assumes you define a line as ending with a newline char. My syntax for fstreams may be off a bit as I hardly ever use that syntax.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  3. struct question
    By caduardo21 in forum Windows Programming
    Replies: 5
    Last Post: 01-31-2005, 03:49 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
Website Security Test