Reputation: 17
If I were given a character array with a maximum length of say 1000 that will always follow the guidelines int,int,char,int
for example "12,6,@,3"
What is the easiest way to separate them and store them to their respective variable type. I know their is such things as isdigit
and such but its really daunting to think of how many nested if
's I would need to interpret these char
s not knowing how many characters each int
could be. I'm very new to programming so please don't be rude I'm just looking for help.
Upvotes: 0
Views: 63
Reputation: 1395
If you are really sure of your input, you could just use sscanf():
#include <stdio.h>
int main(){
typedef struct Ds {
int i1;
int i2;
char c1;
int i3;
} Ds;
Ds ds;
sscanf("12,6,@,3","%d,%d,%c,%d",&ds.i1, &ds.i2, &ds.c1, &ds.i3);
printf("%d,%d,%c,%d\n",ds.i1,ds.i2,ds.c1,ds.i3);
return 0;
}
Upvotes: 2
Reputation: 726669
If the input format is fixed like that, you can use sscanf
:
char inp[] = "12,6,@,3";
int a, b, d;
char c;
if (sscanf(inp, "%d,%d,%c,%d", &a, &b, &c, &d) == 4) {
printf("Received: %d %d %c %d", a, b, c, d);
}
Upvotes: 2