extract text from text

how i extract a word from a text like this code that chervil has sent to me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double extract(const string & buf, string from, string to)
{
    double result = 0;
    
    size_t pos1 = buf.find(from);
    if (pos1 != string::npos)
    {
        pos1 += from.size();
        size_t pos2 = buf.find(to, pos1);
        if (pos2 != string::npos)
        {
            istringstream ss (buf.substr(pos1, pos2-pos1));
            ss >> result;
        }
    }    
    
    return result;
}

i want extract username and password from a text like "login:username=legendarysnake;password=redfox;"
Last edited on
In other words: what does that function do?

First look at lines 5 and 8. What is pos1 after them? What should the from be, if you are looking for username?

Then the line 9. What should the to be?

This extract returns a double. You want a string. That simplifies lines 12-13.


I won't tell the answers, because IMHO you should learn to read code and to know what the standard library (here string::find) does.
i tried change to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 char* extracttext(const string & buf, string from, string to)
{
     char* result ;
   
    size_t pos1 = buf.find(from);
    if (pos1 != string::npos)
    {

        pos1 += from.size();
        size_t pos2 = buf.find(to, pos1);

        if (pos2 != string::npos)
        {
            ostringstream ss (buf.substr(pos1, pos2-pos1));
            //ss >> result;

result= strcpy(result, ss.str().c_str());;
        }
    }    
    
    return result;
}

But won't work
What is the return type of std::string::substr() ?
string?
Yes. There is no question about it; the documentation is clear.

Now, What sounds more appropriate way to return a word from a function: char * or std::string?
In this case there is no need to use a stringstream. Its only purpose was to convert a string into a floating-point number.
Registered users can post here. Sign in or register to post.