![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Apr 2005
Posts: 1
Rep Power: 0
![]() |
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. |
|
|
|
|
|
#2 |
|
Professional Programmer
Join Date: Nov 2004
Posts: 250
Rep Power: 5
![]() |
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;
} |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|