-1

I've been beating my head against the wall for this one for awhile now. What I am trying to do is read a line of input and take the ints from it and store that for later use.

Example inputs:

subi r23, R10, 435

Lb r3, -3(r10)

Example results:

Regarding the 'subi' line I would need 3 variables rs1 = 23, rs2 = 10, and imm = 435. For the Lb I would need rs1 = 3, rs2 = 10, and imm = -3.

There are many different types of inputs and the way they are written so I am looking for the most general method. I thought regex was the answer but I personally couldn't get anything to work and that is perhaps my ignorance to regex. When I say I couldn't get anything to work I mean it, I honestly couldn't post what I tried here because I'm pretty sure I was just making stuff up. Currently I am using this idea:

for(int i = 0; line[i] != '\0'; i++){
    if(isdigit(line[i]) != 0){
       temp += line[i];
       }
}
rs1tmp = temp[1];
rs1 = stoi(rs1tmp);
rs2tmp = temp[2];
rs2 = stoi(rs2tmp);
rdtmp = temp[0];
rd = stoi(rdtmp);

The issue with this idea is that it can only get me every single digit from the line. It doesn't work with double digits or negative numbers. I was thinking about nesting some if statements to check the things next to a digit. So once a digit is found I can look to the left and check if its a "-" and look to the right and check if its a digit. Then take the solution of those if's and push it to a vector.

While I think my idea might work I am really hoping that there is a better way.

Thanks everyone!

Ker
  • 1
  • 2
  • This looks like a computer programming language (specifically, some form of assembly). Such are always parsed by tokenization, never by randomly grabbing numeric data out of each line. Try e.g. Boost Tokenizer, Boost Qi/Spirit, or generate a parser with yacc or bison, not regex. – Ben Voigt Mar 19 '19 at 16:04
  • You sir are a God. Thank you. Used Boost Tokenizer and in less than 20 minutes I have what I need. Thank you. – Ker Mar 19 '19 at 16:56
  • This is my first post. I'm not sure how to mark as "Solved" also should I post the solution I used? – Ker Mar 19 '19 at 16:57
  • You absolutely are allowed to post the essential part of your solution as an answer. There's a time delay mandated by the Stack Exchange platform, but eventually you'll be able to apply the green checkmark, which will transition your question to "solved". – Ben Voigt Mar 19 '19 at 17:41

1 Answers1

0

Ok so using boost::tokenizer I came up with this function and it works perfectly. It grabs all of the numbers positive or negative and stores them into a vector for my later use:

vector<string> getNumbers(string s){
    vector<string> result;
    typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
    s=s.substr(s.find_first_of(" \t")+1);
    boost::char_separator<char> sep{" ,rR()"};
    tokenizer tok{s, sep};

    for (auto it = tok.begin(); it != tok.end(); ++it)
        result.push_back(*it);

return result;

}

Ker
  • 1
  • 2