I have a .txt file divided like this:
(P1, 3): (E10, E20, E1, E3)
(P2, 2): (E10, E20, E2, E5)
(P3, 2): (E10, E20)
I just want to save the numbers of each line in an array. EX: The first one would be [1,3,10,20,1,3]. How can I do that?
Iterate through the file reading it line by line using ifstream.
With the string read to a std::string, use regex search to find the occurences of numbers in the newly read string.
The regex you want to use to extract all the numbers in a string is the following:
https://regex101.com/r/yWJp5p/3
An example of usage:
#include <regex>
#include <iostream>
#include <string>
std::vector<std::string> fetchMatches(std::string str, const std::regex re) {
std::vector<std::string> matches;
std::smatch sm; // Use to get the matches as string
while (regex_search(str, sm, re)) {
matches.push_back(sm.str());
str = sm.suffix();
}
return matches;
}
int main() {
std::string example_input = "(P1, 3): (E10, E20, E1, E3)";
std::regex re{"\\d+"};
auto matches = fetchMatches(example_input, re);
for (const auto& match : matches) {
std::cout << match << std::endl;
}
return 0;
}
There are multiple solutions. Explaining one of the solutions.
Using isDigit and strtol functions of C.
char *str = "(P1, 3): (E10, E20, E1, E3)", *p = str;
while (*p) {
if ( isdigit(*p)) {
long val = strtol(p, &p, 10);
printf("%ld\n", val);
} else {
p++;
}
}
Note: If the file has negative numbers, you will need to check for that.
Just add ((*p=='-'||*p=='+') && isdigit(*(p+1))) in the if condition.
std::stringand parse the string in its own function.operator >>forifstream? I don't remember if it gives an error if it encounters text or just skips it. But could work for you.