I am reading input txt file line by line and trying to get a certain line and extract a number from it. The line can look like this:
"; Max: 144"
"; Max: 28292"
"; Max: 283829"
";Max: 12"
So basically it can have any number of delimeters before "Max: ". I was trying to do it using line.find(...); which tells me if the given sequence is in the line and then erase the unwanted string from it using line.erase(...), but I would have to check every possibility, so it is not well programmed and prone to errors. It looked like this:
size_t pos = line.find("; Max: ");
size_t pos1 = line.find("; Max: ");
size_t pos2 = line.find("; Max: ");
if (pos != -1)
{
std::string x = "; Max: ";
size_t l = x.length();
procs = std::stoi(line.erase(pos, l));
}else if(pos1 != -1){
std::string z = "; Max: ";
size_t l = z.length();
procs = std::stoi(line.erase(pos1, l));
}else if(pos2 != -1){
std::string o = "; Max: ";
size_t l = o.length();
procs = std::stoi(line.erase(pos2, l));
}
...
I was also trying to use regex, but it slowed down my program about 8 times which is highly unwanted. How to extract the number in the fast and proper way?
Here there is an intelligent solution. Use find_first_of
to detect the first digit and then extract the rest of the line.
auto found = line.find_first_of("123456789");
if (found != std::string::npos)
{
procs = std::stoi(line.substr(found));
}
It is supposed that there are not other numbers in the line.