The text to the left and right of the integer is relevant to initialize an object, so it needs to be kept. The starting of the integer will persist and i'm thinking I will try and use a while loop to check to see if the next character is also digit, but I feel like their must be a more elegant solution. Does anyone have any hints, tips, or tricks?
Asked
Active
Viewed 62 times
-2
-
4In C++11, you can use [regex](https://stackoverflow.com/questions/11627440/regex-c-extract-substring) – Seeker Mar 04 '18 at 07:41
-
2Other than pointing you to use [`std::regex`](http://en.cppreference.com/w/cpp/regex/basic_regex), I am afraid it's hard to suggest anything concrete until you post more relevant details. – R Sahu Mar 04 '18 at 08:01
1 Answers
1
Instead of writing a while loop to convert a sequence of charachers to an integer value, the standard library provides std::istringstream
and formatted input (operator>>()
as illustrated by this simple example:
void example1()
{
std::string s{"Hello 1234 World\n"};
std::istringstream ss(s.substr(6,std::string::npos));
int nbr;
ss >> nbr;
std::cout << "The number is " << nbr << std::endl;
}
In this example, the starting position of the string is known. If not, you would need to either parse the string (which in simple cases can be done using similar techniques). For instance, if the number is preceeded by the string "Nbr:", you can use string::find
void example2()
{
std::string s{"Some uninteresting text... Nbr: 1234 World\n"};
auto pos = s.find("Nbr:");
std::istringstream ss(s.substr(pos+4,std::string::npos));
int nbr;
ss >> nbr;
std::cout << "The number is " << nbr << std::endl;
}
Or you can used regex to find the first number in the string and use std::stoi
on the submatch:
void example3()
{
std::string s{"Some uninteresting text... : 1234 World\n"};
std::regex rgx("[^0-9]*(\\d+).*");
std::smatch match;
if (std::regex_search(s, match, rgx)) {
auto n = std::stoi(match[1]);
std::cout << "the number is " << n << '\n';
} else {
std::cout << "no match\n";
}
}

drRobertz
- 3,490
- 1
- 12
- 23