我试图从给定的char数组中解析数学方程式,例如char equation[255] = "4+4";
,我想将第一个数字复制到long number1
,运算符到char oper
第二个数字long number2
.
我已经尝试了,sscanf(equation, "%d%c%d", &number1, &oper, &number2);
但它只是得到第一个数字,无法提取运算符和第二个数字.
试过这个方法:
while (isdigit(equation[k]))
{
k++;
}
oper = equation[k];
Run Code Online (Sandbox Code Playgroud)
但它仍然没有得到运营商.有没有更简单的方法来解析c ++中的方程?
把它变成MCVE ......
#include <stdio.h>
int main()
{
char * equation = "4+4";
long number1, number2;
char oper;
int rc = sscanf( equation, "%d%c%d", &number1, &oper, &number2 );
printf( "%d\n", rc );
if ( rc == 3 )
{
printf( "%d - %c - %d\n", number1, oper, number2 );
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
...给...
3
4 - + - 4
Run Code Online (Sandbox Code Playgroud)
按预期工作.投票结束这个问题,请阅读我在答案开头给出的链接.
也:
如果您确实想使用C++(如原始标记所示),那么Boost.Spirit可满足您的解析需求.