Sscanf make ignore all characters, including newline

I have a line containing data from a file, here is an example

string str = "File:./img/Char2.png\r\n Size:128x128\r\n Frames:2\r\n Hand:79x54\r\n Horizontal_Animated:0" 

And using this line, I hope to initialize the variables, but hit one ploblem: I wanted to use sscanf(str.c_str(),"%*s Size:%dx%d",&Width,&Height) to parse this line, and it works, but there is one thing that I don't like: for the second, third ... sscanf calls I need to add another %*s , because this thing does not ignore \r\n , so the following code looks like this:

 sscanf(contents.c_str(),"%*s %*s Frames:%d",&MaxFrames); sscanf(contents.c_str(),"%*s %*s %*s Hand:%dx%d",&HandX,&HandY) 

So, how do I need to change the format string for right parsing without %*s tones?

ps. I know about regular expressions in C ++ 11, but I'm curious about solutions

+4
source share
1 answer

Since the data is already in std::string , I would first use both std::stringstream and std::getline to split the entire string in strings. Once this is done, sscanf enough to parse individual lines.

With C, stdlib will use strtok to split. But since it modifies the string, you cannot directly use it on std.c_str() . You must first make a modifiable copy using strdup .

But, of course, here you can consider regular expressions.

0
source

All Articles