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.
What is an elegant way of separating the console input (or a string) into two int variables?
Input format: a - bx
Result:
int1 = a;
int2 = -b;
Any hints appreciated.
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.
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.