我想制作一个解析器,我想到的第一步是从输入字符串中提取整数和运算符,并将它们存储在各自的数组中。到目前为止我所拥有的是......
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Grammar for simple arithmetic expression
E = E + T | E - T | T
T = T * F | T / F | F
F = (E)
Legend:
E -> expression
T -> term
F -> factor
*/
void reader(char *temp_0){
char *p = temp_0;
while(*p){
if (isdigit(*p)){
long val = strtol(p, &p, 10);
printf("%ld\n",val);
}else{
p++;
}
}
}
int main(){
char expr[20], temp_0[20];
printf("Type an arithmetic expression \n");
gets(expr);
strcpy(temp_0, expr);
reader( temp_0 );
return 0;
}
假设我有一个“65 + 9 - 4”的输入,我想将整数 65、9、4 存储到一个整数数组中,并将运算符 +、- 存储在一个运算符数组中,同时忽略输入中的空格.我应该怎么做?
附言 我在阅读器函数中使用的代码是从这里获得的:How to extract numbers from string in c?
最佳答案
我写了一个示例测试。 抱歉,代码太难了,因为没有太多时间。 但它在我的 VS 上运行良好。
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include <ctype.h>
int main(){
//Here I think By default this string is started with an integer.
char *str = "65 + 9 - 4";
char *ptr = str;
char ch;
char buff[32];
int valArray[32];
int val, len = 0, num = 0;
while ((ch = *ptr++) != '\0'){
if (isdigit(ch) && *ptr != '\0'){
buff[len++] = ch;
}
else{
if (len != 0){
val = atoi(buff);
printf("%d\n", val);
valArray[num++] = val;
memset(buff, 0, 32);
len = 0;
}
else if (ch == ' ')
continue;
else
printf("%c\n",ch);
}
}
}
关于c - 如何从c中的字符串中分离整数和运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599883/