当前位置: 动力学知识库 > 问答 > 编程问答 >

I need help interpreting char arrays in C

问题描述:

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 chars 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.

网友答案:

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);
}

Demo.

网友答案:

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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: