find string in text file

I've just completed my first instructional c++ book and am still trying to figure out a few things. I'm making assignments for myself to better learn this language and understand the parts of it that I am going to use when I've become much more proficient using it.
My ultimate goal is to open a text file, like a markup file(xml, html, etc) and search for a specific tag, and then assign the contents of the tag into a variable.
However, despite reading at least 20 forum threads, reviewing my book, and searching tutorials; I cannot seem to figure out how to just simply search the text file that I've opened for a specific string.
I've been trying to figure out how to use the string class' find(), or getline() functions to find the open tag of an element within the document, or even just a string of text within the document.
I'm sure that as new as I am to this, I'm surely going in the wrong direction.
Can anybody please help guide me in the right direction? I'm just wanting to learn how to search the text file for a specified string. Any relevant suggestions would be greatly appreciated.
Last edited on
You need to open the file and read some or all of its contents into a string. Once there, you can transform (for example, to lowercase) and search using find() or whatever.

You can do it line by line:

1
2
3
4
5
6
7
8
9
10
11
ifstream file( ... );
while (getline( file, s ))
  {
  ...
  if (s.find( ... ))
    {
    ...
    break;
    }
  }
file.close();

You can do it all at once:
This method, BTW, has the advantage of automatic newline transformations, so you can assume the string contains only "\n" between lines instead of "\r\n" or "\r".

1
2
3
#include <fstream>
#include <streambuf>
#include <string> 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::string& loadfile( const std::string& filename, std::string& result )
  {
  std::ifstream f( filename.c_str() );
  if (f)
    {
    f.seekg( 0, std::ios::end );
    result.reserve( f.tellg() );
    f.seekg( 0, std::ios::beg );
    result.assign(
      (std::istreambuf_iterator <char> ( f )),
       std::istreambuf_iterator <char> ()
      );
    }
  return result;
  }
1
2
3
string s;
loadfile( ..., s );
s.find( ... );

Don't forget those extra parentheses on line 10 -- they're important.

Hope this helps.
Topic archived. No new replies allowed.