Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can scanf/sscanf deal with escaped characters?

Tags:

c++

c

int main()
{
  char* a = " 'Fools\' day' ";
  char* b[64];
  sscanf(a, " '%[^']s ", b);
  printf ("%s", b);
}

--> puts "Fools" in b

Obviously, I want to have "Fools' day" in b. Can I tell sscanf() not to consider escaped apostrophes as the end of the character sequence?

Thanks!

like image 419
st12 Avatar asked Feb 27 '23 17:02

st12


1 Answers

No. Those functions just read plain old characters. They don't interpret the contents according to any escaping rules because there's nothing to escape from — quotation marks, apostrophes, and backslashes aren't special in the input string.

You'll have to use something else to parse your string. You can write a little state machine to read the string one character at a time, keeping track of whether the previous character was a backslash. (Don't just scan to the next apostrophe and then look one character backward; if you're allowed to escape backslashes as well as apostrophes, then you could end up re-scanning all the way back to the start of the string to see whether you have an odd or even number of escape characters. Always parse strings forward, not backward.)

like image 67
Rob Kennedy Avatar answered Mar 03 '23 14:03

Rob Kennedy