Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract integers from std::string

Tags:

c++

c++11

I'm writing simple OBJ loader and I encountered next problem - I have to extract integers from next std::string:

f v0/vt0/vn0 v1/vt1/vn0 ... vk/vtk/vnk

where vk, vtk, vnk are int values and there is no space between / and the values and only one space between groups.

As the files can be quite large and this type of lines may appear more than 100000 times I need an efficient way to extract the integers from strings like this one.

EDIT:

As Jesse asked this is my current approach(I assume data is in the right format!):

int p, t, n;
const char* l = line.c_str() + 2;

for (int vIndex = 0; l && sscanf(l, "%d/%d/%d", &p, &t, &n) == 3; ++vIndex)
{
    //do something with vertex
    l = strchr(l, ' ');
    if (l)
    {
        l += 1;
    }    
}
like image 340
Mircea Ispas Avatar asked Mar 22 '23 15:03

Mircea Ispas


1 Answers

Use std::strtol, this is quite neat in that it will return the end of the current parse, and you can continue from there. So let's say that you guarantee that you read three digits each time, something like the following sketch could work..

char *p = line.c_str() + 1;

while (p)
{
  long v0 = std::strtol(++p, &p, 0); // at the end, p points to '/'
  long v1 = std::strtol(++p, &p, 0); // at the end, p points to '/'
  long v2 = std::strtol(++p, &p, 0); // at the end, p points to ' '
  // On the last one, p will be null...
}
like image 69
Nim Avatar answered Mar 24 '23 05:03

Nim