debugging - Parsing a string into typedef structure in C -


how parse string file contains characters , numbers typedef structure.

those 2 lines example of data needs parsed:

pebbles flintstone4female bam-bam rubble3male 

first name, space , followed surname, age , gender.

name, surname, age , gender parts of typedef needs stored.

there total of 7 string 2 above stored in .txt file.

how write correct buffer separate string?

this i've got far

sscanf(buffer, "%[^ ]%*[^1234567890]%d%s", buff_name, buff_surname, buff_age, buff_gender); 

but doesn't seem work , cannot access information it.

  1. always check return value sscanf() , relatives.
  2. do enable compiler warnings. compiler tell next issue:
  3. do not suppress assignment using * in %*[0-9] when want surname read.

note sscanf() line doesn't use data structure mention. however, sample code does:

#include <stdio.h>  typedef struct {     char name[20];     char surname[20];     int  age;     char gender[7]; } who;  int main(void) {     const char *data[2] =      {         "pebbles flintstone4female",         "bam-bam rubble3male",     };     const char *fmt[2] =     {         "%[^ ]%*[^1234567890]%d%s",         "%[^ ]%[^1234567890]%d%s",     };      (int = 0; < 2; i++)     {         (int j = 0; j < 2; j++)         {             buff;             int n;             if ((n = sscanf(data[j], fmt[i], buff.name, buff.surname, &buff.age, buff.gender)) != 4)                 printf("oops: format \"%s\", n = %d: %s\n", fmt[i], n, data[j]);             else                 printf("format \"%s\": data %s: %s %s %d %s\n",                        fmt[i], data[j], buff.name, buff.surname, buff.age, buff.gender);         }     }     return 0; } 

sample output:

oops: format "%[^ ]%*[^1234567890]%d%s", n = 3: pebbles flintstone4female oops: format "%[^ ]%*[^1234567890]%d%s", n = 3: bam-bam rubble3male format "%[^ ]%[^1234567890]%d%s": data pebbles flintstone4female: pebbles  flintstone 4 female format "%[^ ]%[^1234567890]%d%s": data bam-bam rubble3male: bam-bam  rubble 3 male 

if compile string literal sscanf() format, gcc warn problem:

td.c: in function ‘main’: td.c:23: warning: format ‘%d’ expects type ‘int *’, argument 4 has type ‘char *’ td.c:23: warning: format ‘%s’ expects type ‘char *’, argument 5 has type ‘int *’ td.c:23: warning: many arguments format 

the code above different format strings can't give warning.

the format strings should modified avoid buffer overflows, too:

"%19[^ ] %19[^0-9] %d %6s" 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -