Reputation: 243
Consider a string of the form
"number of columns = 5
number of rows = 345
1 3 -5 2 9
4 -10 34 -22 7"
[There are 343 more rows followed by this. However, I guess it will be enough to explain the problem.]
I wish to extract the values 5
and 345
as integers. The substrings "number of columns = " and "number of rows = " are known but the number of digits in the values followed by these strings is not known. However, it is known that the corresponding line ends after the value. I can get to the beginning of the number using the following code
std::string searchString = "clause length = ";
int searchStringLength = searchString.length();
std::size_t startAt = result.find(searchString) + searchStringLength;
However, I don't know how to detect the end of a line, using which I can extract the values.
And the next part is to extract the rest of the integers and store them in an array and I think if I can identify the positions of the empty spaces and the end of lines, this problem will also get resolved.
How can I solve this problem efficiently [I am using Visual Studio 2017]?
Upvotes: 0
Views: 79
Reputation: 1982
Try the following simple number extractor based on regex
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
int main()
{
std::string s = "number of columns = 5\n"
"number of rows = 345\n"
"1 3 -5 2 9\n"
"4 -10 34 -22 7\n";
std::regex num_regex("\\d+|-\\d+");
auto num_begin =
std::sregex_iterator(s.begin(), s.end(), num_regex);
auto num_end = std::sregex_iterator();
for (std::sregex_iterator i = num_begin; i != num_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
std::cout << " " << match_str << '\n';
}
}
Output
5
345
1
3
-5
2
9
4
-10
34
-22
7
Upvotes: 2
Reputation: 19
You can split the string into tokens. In this case split the string according to "=" sign and then try to convert them into integer's http://www.cplusplus.com/reference/cstring/strtok/ Go through this link
Upvotes: 0