c - How can I resolve sscanf issue with email? -


here's code:

#include <stdio.h>  int main(int argc, char **argv) {     const char example[]="13902796d ; josefa moral fidalgo ; someone@server.com ; 01/03/2001 ; 0 ; 1 ;";     char dni[10];     char name[100];     char email[100];     char date[10];     int gender;     int uni;      sscanf(example, "%[^;] ; %[^;] ; %[^;] ; %[^;] ; %d ; %d ; ",         dni, name, email, date, &gender, &uni);      printf("dni: %s\n", dni);     printf("name: %s\n", name);     printf("email: %s\n", email);     printf("date: %s\n", date);     printf("gender: %d\n", gender);     printf("uni: %d\n", uni);     return 0; } 

and here's result:

dni: 13902796d name: josefa moral fidalgo email: date: 01/03/2001 gender: 0 uni: 1 

but expect result:

dni: 13902796d name: josefa moral fidalgo email: someone@server.com date: 01/03/2001 gender: 0 uni: 1 

i'm newbie c, can't find answer on internet, nor here on stackoverflow, , check books can't find reason why code

 sscanf(example, "%[^;] ; %[^;] ; %[^;] ; %[^;] ; %d ; %d ; ",             dni, name, email, date, &gender, &uni); 

doesn't work. can me? can't use other functions sscanf, that's professor wants use in code.

buffer overflow.

how code know not overfill dni[]? address of dni passed sscanf(). since op's code did not provide enough space input, dni[] overwritten leading undefined behavior (ub).

sscanf(example, "%[^;] ... ", dni, .... 

instead, pass maximum number of characters read, width. 9 limit scan 9 characters. array size 10, there enough memory 9 characters , appended null character. code needs make buffers larger accommodate user input.

char dni[10*2]; sscanf(example, "%19[^;] ... ", dni, .... 

but entire scan right?
simple method record offset of scan " %n". if scan reached "%n", n have new value.

int n = -1; sscanf(example, "%9[^;] ;...  %n", dni, ..., &n); 

put together

int main(int argc, char **argv) {     const char example[]="13902796d ; 1 ;";     char dni[10*2];     int uni;      int n = -1;     sscanf(example, "%19[^;] ; %d ; %n", dni, &uni, &n);     if (n < 0) {       puts("fail");     } else {       printf("dni: %s\n", dni);       printf("uni: %d\n", uni);     }     return 0; } 

code still has issues dni[] "13902796d " (note trailing space), issue op handle.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -