开发者

C separate a string into 4 variables

开发者 https://www.devze.com 2023-04-11 14:09 出处:网络
I\'d want to separate a string into 4 parts. What I need is basically this: sscanf(string, \"%d %d %d %[^\\n]\", id1, id2, id3, restOfString);

I'd want to separate a string into 4 parts. What I need is basically this:

sscanf(string, "%d %d %d %[^\n]", id1, id2, id3, restOfString);

The var restOfString is a char* Problem: restOfString must point to the smallest space of memory possible and still contain all the string indicated by the %[^\n].

I wanted just about what asprintf does. It has an internal malloc() that creates the memory space needed to print the开发者_JAVA百科 string. I wanted the same technique for sscanf(). How can I accomplish that? How can I know the size of the string sscanf() will read?


I completely agree with RushPL about not bothering to micro-optimize for memory. In the more general case, though, where you might have a large string and comparatively small restOfString, here's an approach that aliases restOfString to the main string:

// char *string, *restOfString;
// int id1, id2, id3, id4;
int result, numStored;
result = sscanf(string, "%d %d %d %d %n", &id1, &id2, &id3, &id4, &numStored);
if (result == 4)
    restOfString = string + numStored;
else
    restOfString = 0;

Basically, use %n to grab the current position while parsing, and then use that as an offset into the original string. Note that %n is a specifier that is very likely to cause format-string vulnerabilities if used carelessly. If you're doing complicated parsing, you shouldn't be using scanf and friends.


Just use char* restOfString = malloc(strlen(string)); the few extra bytes will not matter if the whole rest of the string is too big to fit on stack. Getting the exact malloc size would be counter productive.

Alternatively if I may suggest, you can skip allocation altogether (but it depends on your needs). As sscanf returns number of elements and note bytes read, you could find the position of rest of the string manually. Not pretty but should work.

// sscanf 
sscanf(string, "%d %d %d");
const char* restOfString = strchr(strchr(strchr(string, ' ') + 1, ' ')+1, ' ')+1; // third ' ' +1 gives rest of string

Alternatively, you can get exact allocation using:

char* restOfStringAlloced = strdup(restOfString);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号