首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将整数和运算符从c中的字符串中分离出来?

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

Stack Overflow用户
提问于 2015-09-16 04:35:49
回答 1查看 1.7K关注 0票数 1

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

代码语言:javascript
运行
复制
#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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-16 05:59:54

我写了一个样本测试。抱歉,代码太难了,因为没有太多的时间。但在我的VS上效果很好。

代码语言:javascript
运行
复制
#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);
            }
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32599883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档