將控制檯輸入(或字符串)分離爲兩個int變量的優雅方式是什麼?C++單獨輸入到各種變量中
輸入格式:a - bx
- a,b是整數總是。
- x可以忽略。
結果:
int1 = a;
int2 = -b;
理解任何提示。
將控制檯輸入(或字符串)分離爲兩個int變量的優雅方式是什麼?C++單獨輸入到各種變量中
輸入格式:a - bx
結果:
int1 = a;
int2 = -b;
理解任何提示。
準確假設的形式表示:
int a, b;
std::string op;
std::cin >> a >> op >> b;
if (op == "-") b = -b;
注意,這是不穩健。它會將除-
以外的任何內容視爲加號,並且將絕對地識別任何以由非空白字符分隔的數字對開始的輸入。
如果輸入是: - a - bi? – xBlue
然後它不會工作。如果你想要一個更強大的解決方案,你需要構建一個小的解析器。 –
將字符串標記並解析爲數學方程。
使用C++ 11和AX這裏是一個可能的語法分析程序:
#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.謹防上述代碼中的錯誤:我只證明它是正確的,沒有嘗試過。
類似於:http://stackoverflow.com/questions/1806074/c-extract-polynomial-coefficients – HostileFork