0

What is an elegant way of separating the console input (or a string) into two int variables?

Input format: a - bx

  • a, b are integer always.
  • x can be ignored.

Result:

int1 = a; 
int2 = -b;

Any hints appreciated.

1

3 Answers 3

1

Assuming exactly the form stated:

int a, b;
std::string op;
std::cin >> a >> op >> b;
if (op == "-") b = -b;

Note that this isn't robust. It'll treat anything other than - as a plus, and will recognise absolutely any input that starts with a pair of numbers separated by a blob of non-whitespace.

Sign up to request clarification or add additional context in comments.

1 Comment

Then it won't work. If you want a more robust solution, you'll need to build a small parser.
1

Tokenize and parse string as math equation.

Comments

0

Using C++11 and AXE here is a possible parser:

#include <axe.h>
#include <iostream>

template<class I>
void example(I i1, I i2)
{
    int a, b;
    auto space = axe::r_lit(' ');
    auto rule = axe::r_udecimal(a) & *space & axe::r_decimal(b);
    (rule >> axe::e_ref([&](...) 
    { std::cout << "\na=" << a << ",b=" << b; }))
    (i1, i2);
}

int main()
{
    std::string str = "100 - 10i";
    example(str.begin(), str.end());
}

P.S. Beware of bugs in the above code: I have only proved it correct, not tried it.

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.