Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Apr 25th, 2005, 10:12 AM   #1
quizquiz
Newbie
 
Join Date: Apr 2005
Posts: 1
Rep Power: 0 quizquiz is on a distinguished road
file problem

Hi, i have a txt file and im writing a program(on c++) to read that file
ang go to a specify line.
how can i do that????
i had a lot of problems.
thanks.
quizquiz is offline   Reply With Quote
Old Apr 25th, 2005, 11:09 AM   #2
Eggbert
Professional Programmer
 
Eggbert's Avatar
 
Join Date: Nov 2004
Posts: 250
Rep Power: 5 Eggbert is on a distinguished road
The easiest solution is to read the lines of your file into a vector. Then you have the entire file in memory and can access lines using either an iterator or an index.
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
  string line;

  cout<<"Enter a file to open: ";

  if ( !getline ( cin, line ) ) {
    cerr<<"Input error"<<endl;
    return EXIT_FAILURE;
  }

  ifstream in ( line.c_str() );

  if ( !in ) {
    cerr<<"File open failure"<<endl;
    return EXIT_FAILURE;
  }

  // Copy the file into memory
  vector<string> file;

  while ( getline ( in, line ) )
    file.push_back ( line );

  // If the file was not exhausted, flag an error
  if ( !in.eof() )
    cerr<<"Error reading file"<<endl;

  // Display the entire contents of the file
  vector<string>::iterator it = file.begin();
  vector<string>::iterator end = file.end();

  while ( it != end )
    cout<< *it++ <<endl;

  // Locate a single line
  cout<<"The 5th line is ";

  if ( file.size() >= 5 )
    cout<<'\"'<< file[5] <<'\"'<<endl;
  else
    cout<<"not present"<<endl;
}
Eggbert is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 9:23 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC