c - Sscanf doesn't give me a value -
i have piece of code:
if(string_starts_with(line, "name: ") == 0){ //6th first char of name char name[30]; int count = 6; while(line[count] != '\0'){ name[count-6] = line[count]; ++count; } printf("custom string name: %s", name); strncpy(p.name, name, 30); } else if(string_starts_with(line, "age: ") == 0){ //6th first char of name printf("age line: %s", line); short age = 0; sscanf(line, "%d", age); printf("custom age: %d\n", age); }
the if
works, else if
doesn't work. example output is:
person: name: great custom string name: great age: 6000 age line: age: 6000 custom age: 0
i have changed lot, using &age
in sscanf
function, nothing works.
if want store value short
(why¿?) need use appropriate length modifier. also, if expecting number come after prefix string, need start scan after prefix string. finally, mention in passing, necessary give sscanf
address of variable in want store value.
and remember check return value of sscanf
make sure found number.
in short:
if (sscanf(line + 5, "%hd", &age) != 1) { /* handle error */ }
several of these errors (but not of them) have been shown if had compiled warnings enabled. gcc or clang, use -wall
in compiler options.
Comments
Post a Comment