Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Retrieving a particular line from list<string> (http://www.go4expert.com/forums/retrieving-particular-line-liststring-t16824/)

batcave109 7Apr2009 04:33

Retrieving a particular line from list<string>
 
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.

xpi0t0s 8Apr2009 04:36

Re: Retrieving a particular line from list<string>
 
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().

batcave109 8Apr2009 19:23

Re: Retrieving a particular line from list<string>
 
Quote:

Originally Posted by xpi0t0s (Post 45475)
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

xpi0t0s 8Apr2009 19:47

Re: Retrieving a particular line from list<string>
 
Sorry about that; I should have RTFM...I never can remember parameter lists.


All times are GMT +5.5. The time now is 15:56.