简体   繁体   中英

Parsing a C string and storing parts of the string in variables

This post might be marked as a duplicate, but I did search online for this specific case and I couldn't find any examples similar to this. The following is a simplified version of my code.

I have the following lines of data stored with a text file named test.txt :

12345|This is a sentence|More words here
24792|This is another sentence|More words here again

The text in the test.txt file will always follow the format of <int>|<string>|<string>

I now want to store each of the sections separated by the delimiter |in a variable.

The following is my attempt:

uint32_t num;
char* str1, str2;

// the data variable is a char pointer to a single line retrieved from test.txt
sscanf(data, "%d|%s|%s", &num, str1, str2);

This code above would retrieve the correct value for num but would insert the first word from section two into str1 , leaving the variable str2 as null. To my understanding, this was the case because the sscanf() function stops when it hits a space.

Is there an efficient way of storing each section into a variable?

As you noted, %s uses whitespace as the delimiter. To use | as the delimiter, use %[^|] . This matches any sequence of characters not including |.

And since num is unsigned, you should use %u , not %d .

sscanf(data, "%u|%[^|]|%[^|]", &num, str1, str2);

Don't forget to allocate memory for str1 and str2 to point to; scanf() won't do that automatically.

Your variable declarations are also wrong. It needs to be:

char *str1, *str2;

Your declaration is equivalent to:

char *str1;
char str2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM