Reputation: 47
Hey Im having a problem trying to parse strings. My program can receive 4 types of input:
s = "x=10+2;"
s = "x=10+y;"
s = "x=y+10;"
s = "x=y+z;"
I mean the format is something like: s = "(string)=(string)||(int)+(string)||(int);"
I have tried to use sscanf( s, "%c=%d+%d", &c, &v1, &v2 )
but I need to first verify which type of input is it.
char* s = "x=2+22;";
int v1, v2;
char* c;
sscanf( s, "%c=%d+%d", &c, &v1, &v2 );
printf("%s %d %d\n", c, v1, v2);
I want to parse the string to three vars.
Upvotes: 0
Views: 84
Reputation: 407
Let me propose you another way, using strsep
and some if
conditionals to detect if the characters are integer or string, the following code works for all your cases
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *token, *string, *var;
char *str = "x=x+10;";
int tmp1,tmp2;
tofree = string = strdup(str);
if (string == NULL)
return -1;
token = strsep(&string, "=");
printf("%s\n", token);
token = strsep(&string, "=");
printf("%s\n", token);
var = strsep(&token, "+");
if( var[0] >= 0x60 && var[0] <= 0x7B ) // detect string
{
printf("str1 = [ %s ] \n", var);
} else { // else case will be an integer
tmp1 = atoi(var);
printf("int1 = [ %d ] \n ",tmp1);
}
var = strsep(&token, "+");
var[strlen(var)-1]='\0'; // remove ";"
if( var[0] >= 0x61 && var[0] <= 0x7A )
{
printf("str2 = [ %s ] \n", var);
}else{
tmp2 = atoi(var);
printf("int2 = [ %d ] \n ",tmp2);
}
return 0;
}
Upvotes: 1