繁体   English   中英

如何从c中的字符串中分离出整数和运算符?

[英]how to separate integers and operators from a string in c?

我想做一个解析器,我要记住的第一步是从输入字符串中提取整数和运算符,并将它们存储在各自的数组中。 到目前为止,我有这...

#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存储到一个整数数组中,并将运算符+,-存储在一个运算符数组中,并且也忽略输入中的空格。 我该怎么办?

PS我在我的阅读器功能中使用的代码,我从这里得到: 如何从c中的字符串中提取数字?

您可以将整数数组和运算符数组作为render( temp_0, arrNum, arrOperator, &numCount, &opCount)类的参数传递给render()函数,其中arrNum是long数组,而arrOperator是char数组, numCountopCount是两个整数,分别表示整数和运算符的数量。 最后两个整数将填充在render() 然后,修改后的render()函数可能类似于:

void reader(char *temp_0, long *arri, char *arro, int *numCount, int *opCount){
char *p = temp_0;
int integerCount = 0;
int operatorCount = 0;

while(*p){
    if (isdigit(*p)){
        long val = strtol(p, &p, 10);
        arri[integerCount++] = val;
    }else{
       if((*p == '+') || (*p == '-') || 
          (*p == '/') || (*p == '*'))/* Add other operators here if you want*/
       {
          arro[operatorCount++] = *p;
       }
    p++;
    }
}

    *numCount = integerCount;
    *opCount  = operatorCount;

}

请注意,代码中没有进行错误检查。 您可能要添加它。

我写了一个样本测试。 很抱歉,因为没有太多时间,所以代码很难。 但这在我的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);
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM