Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to move backwards and extract the whole line in which 'new' occurs.

C++
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
  {
char word[30];
  string filename;
  
  cout << "Name your file> ";
  getline( cin, filename );

  fstream file( filename.c_str() );
  if (!file)
    {
    cout << "I could not open the file. Fooey.\n";
    return EXIT_FAILURE;
    }
  else 
    {
    string line;
    
    while (!file.eof())
      {
          file >> word;
		if(strcmpi(word,"new")==0)		
           {
			/*getline( file, line );
				cout << line;*/
		}

	 
     
      }
    file.close();
    }

  return EXIT_SUCCESS;
  }
Posted
Updated 24-Jan-12 0:12am
v2

Why don't you read the file line by line (using std::getline[^]), and search the "new" string inside the line? This way (on successful find[^] call) you already have the needed line.


[updated]
Something like this (not tested):
C++
do
{
  getline( file, line);
  if ( ! file.good() ) break; // end of file or some other error
  if ( line.find("new") != string::npos)
  {
    // found: here 'line' is the wanted line.
  }
} while ( true );

[/updated]
 
Share this answer
 
v2
Comments
Espen Harlinn 24-Jan-12 6:25am    
5'ed!
CPallini 24-Jan-12 6:37am    
Thank you.
Shmuel Zang 24-Jan-12 6:28am    
5'ed.
CPallini 24-Jan-12 6:37am    
Thanks.
@cpallini - thanx a lot for your help.. can you please write in a little code snippet to solve my problem. i am very new to programming.. i tried what you suggested but in vain..thanx again
 
Share this answer
 
Thank you so much it worked....Its my first assignment ..taht is why i am getting stuck at stupid things...i am really thankful to you that you took out time for solving my problem ..thanks once again
 
Share this answer
 
can you tell me how to identify the pointer variable's name after extracting the lines with 'new' statement.. i am developing a parser to detect memory leaks.
for ex I have
int* p = new int;
i need 'p' to be stored in a map. so as to make sure that it is deleted later on
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900