Thread: need help with a basic prog (reading input files)

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    2

    need help with a basic prog (reading input files)

    Hi, I decided to write a prog that requires me to open an external data file and read and manipulate each line of the file one at a time. I have never taken any classes so I dont have a book, just read a few tutorials online. I cant find seem to find the syntax I need though for this problem. I actually have the data file open, using a tut that used this syntax:
    Code:
    int main () {
      string line;
      ifstream myfile ("myfile.txt");
      if (myfile.is_open())
      {
        while (! myfile.eof() )
        {
          
          cout << line << endl;
        }
        
      }
    
      else cout << "Unable to open file"; 
    
      return 0;
    but It doesnt go into any further detail about how to go about reading line by line. Like for instance if the file has a list of names that has to be changed then placed back in the file or output.

    Any suggestions? Help is greatly appreciated.

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    The best way to read the file is to use getline():

    Code:
    std::ifstream in( "myfile.txt" );
    if ( in ) {
      std::string line;
      while( std::getline( in, line ) ) {
        std::cout<< line << "\n";
      }
    }
    in.close();
    If you're unfamiliar with using 'std::' just ignore them. I prefer not to use "using namespace std;" globally.

    A 'problem' arises though when you wish to change the contents of a file. You cannot really simply change a line. You have to read in the whole contents of a file manipulate it and save it to another file and delete the original (so you don't loose data on bad luck). (or read line by line or block by block if the file's large).

    You could alternatively look into fstream's rather than ifstreams and ofstreams but maybe get used to them first.

  3. #3

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    2
    That is what I need twomers. Thank you very much. Thanks robwhit too. The cplusplus site seems really helpful.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. writing and reading files
    By oldie in forum C Programming
    Replies: 1
    Last Post: 07-03-2008, 04:54 PM
  3. Replies: 5
    Last Post: 02-25-2008, 06:35 AM
  4. Issues reading text files
    By ozzy34 in forum C++ Programming
    Replies: 5
    Last Post: 06-01-2004, 08:15 AM
  5. reading from other files one char at a time
    By jmoney in forum C Programming
    Replies: 10
    Last Post: 02-24-2003, 06:18 PM