我想要做一个解析器,我想到的第一步是从输入字符串中提取整数和运算符,并将它们存储在各自的数组中。到目前为止我所拥有的是..。
#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?
发布于 2015-09-16 05:59:54
我写了一个样本测试。抱歉,代码太难了,因为没有太多的时间。但在我的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);
}
}
}
https://stackoverflow.com/questions/32599883
复制相似问题