0

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?

2
  • 1
    You probably want to read 1 line at a time into a std::string and parse the string in its own function. Commented Nov 3, 2019 at 22:47
  • Have you tried operator >> for ifstream? I don't remember if it gives an error if it encounters text or just skips it. But could work for you. Commented Nov 3, 2019 at 22:49

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.