[英]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數組, numCount
和opCount
是兩個整數,分別表示整數和運算符的數量。 最后兩個整數將填充在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.