Retrieving a particular line from list<string>

batcave109's Avatar, Join Date: Apr 2009
Newbie Member
Hi, I have read a .txt file into a list<string> container and now I am trying to pull out individual lines that meet certain criteria. For example the text file I am reading from is layed out like a table:
Name age sex
Peter 25 m
Paul 32 f
Jenny 19 f

I want to retrieve a line by searching for the name e.g passing a "Peter" argument will return "Peter 25 m" and afterwards I want to split this line up into individual elements "Peter", 25 and 'm'
How would I go about this?
Here is the code I have so far.

Code:
int main()
{    
    string temp;
    ifstream fileInput;
    list<string> L;

    fileInput.open("Data.txt");
    if(!fileInput)
        {
            cerr<< "file cannot be found";
        }
    else
        {
            while( getline(fileInput, temp)){
                 L.push_back( temp ); 
             }
        }
and then to try and pull individual lines out

Code:
std::list<std::string>::iterator i;

    for (i = input.begin(); i != input.end(); ++i)
{
   if (*i == "Peter 25 m")
   {
      break;
   }
}

if (i != input.end())
{
    std::cout<< *i;
}
else
{
    std::cout  "not found line";
}
The above snippet works however it only outputs the line if the full line is matched exactly instead of just matching the name.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
The C function strstr() tells you if a string exists within another string, e.g. strstr("Peter","Peter 25 m") would return TRUE. I'm not sure if std::string has anything like that; if not then you would need to call c_str() for the parameters to strstr().
0
batcave109's Avatar, Join Date: Apr 2009
Newbie Member
Quote:
Originally Posted by xpi0t0s View Post
The C function strstr() tells you if a string exists within another string, e.g. strstr("Peter","Peter 25 m") would return TRUE. I'm not sure if std::string has anything like that; if not then you would need to call c_str() for the parameters to strstr().
That works, however the arguments are the reverse of what you put e.g strstr("Peter 25 m", "Peter") instead of strstr("Peter", "Peter 25 m") and I did have to call c_str() like you said.
Thanks
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Sorry about that; I should have RTFM...I never can remember parameter lists.