0
votes

I have a string that contains information separated by | characters, and I need to create substrings for each piece of information. Additionally, some of the fields may be blank.

The order of values goes FirstName|LastName|Age|IDNumber|Height|Weight

So possible strings could be:

char* strA = "John|Doe|50|123456|70|150"; char* strB = "James|Smith|40|345678||";

I am able to pull out the first field just fine using sscanf, but when I attempt to grab multiple fields I get the wrong values.

In order to get the first value, I can call

char* strA = "John|Doe|50|123456|70|150";
char* a, b;
sscanf(strA, "%[^|]|", &a);
printf("%s\n", &a);

which prints John But when I attempt to get the first 2 fields by calling

char* strA = "John|Doe|50|123456|70|150";
char* a, b;
sscanf(strA, "%[^|]|%[^|]|", &a, &b);
printf("%s | %s\n", &a, &b);

It prints oe | Doe

I cannot figure out why that is.

1
The pointer a char* a, b; is not initialized. - Vlad from Moscow
Don't use & when calling printf. - Barmar
@Barmar that results in a segmentation fault for me - Sam Hinkie
@VladfromMoscow but the values are set in the call to sscanf, why would it work when only looking for the first field but then break when looking for the first 2? - Sam Hinkie
Your (a) lack of setting a and b to point to any valid memory, and (b) sending a and b by address (so the addresses of the pointers, not what they should be pointing to), are compounding your problems. - WhozCraig

1 Answers

1
votes

Your pointer setup is wrong. Either use dynamic or automatic allocation. Also, your arguments to sscanf for format %[^|] are likewise wrong. That expects a char* and your delivering a char** in the &a case, and a simple pointer to char (one) in the &b case. Both should be referring to memory ample to consume your input.

Example (using automatic storage)

const char* strA = "John|Doe|50|123456|70|150";
char a[32], b[32];
sscanf(strA, "%31[^|]|%31[^|]|", a, b);
printf("%s | %s\n", a, b);

Frankly, nearly any modern toolchain worth its salt should have warned you of the improper types being sent to scanf and printf. Turn up your warnings and/or use a toolchain developed in this millennium.