Link to home
Start Free TrialLog in
Avatar of antonumia
antonumiaFlag for United States of America

asked on

display 20 characters on each side of a strstr result

i am doing a little app that requests a search term, opens a file, loops through the file looking for the search and displays each occurence of the term on screen.

after i find the term using:

    inFile.getline(buf, 299, '\n');
    char * pch;
    pch = strstr (buf,searchTerm);

i want to set the pointer 10 characters back in the file and then extend the length of the substring by the searchTerm and another 10 characters e.g.

nnnnnnnnnn searchTerm nnnnnnnnnn

so it is centred and we can see the text either side of the search term.

another problem i forsee is if the search term is found less than 10 characters from the start or end of the string in 'buf'
Avatar of n_fortynine
n_fortynine

seekg() should do the trick.
(MS def)
istream& seekg( streamoff offset, ios::seek_dir dir );
to set it back 10 characters simply do something like:
inFile.seekg(-10,ios::cur);
>> if the search term is found less than 10 characters >>from the start or end of the string in 'buf'
in this case you can check if(ios::cur - ios::beg > 10) or something like that.

if(ios::cur - ios::beg > 10)
//do the move back 10.
  inFile.seekg(-10, ios:cur);
else
//set to the beginning
  inFile.seekg(ios::beg);
ASKER CERTIFIED SOLUTION
Avatar of n_fortynine
n_fortynine

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of antonumia

ASKER

thanks,

btw: it didn't work until i cleared the stream state first.

e.g.
inFile.clear();
inFile.seekg(n,ios:beg);