Serious Dabbler

scanf specifying set of valid characters

leave a comment »

Today, as I was being frustrated over yet again the absence of a scanf function that reads into an std::string, or more generally of the fact that most of the input/output functions still deal with char* and then need to be converted to std::string, I stumbled upon this neat little fact that was not mentioned on the cplusplus reference page, and that is the ability to specify a set of characters to extract using scanf instead of %s.

Quote from the man page of scanf:

[ –  Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer to char, and there must be enough room for all the characters in the string, plus a terminating null byte. The usual skip of leading white space is suppressed. The string is to be made up of characters in (or not in) a particular set; the set is defined by the characters between the open bracket [ character and a close bracket ] character. The set excludes those characters if the first character after the open bracket is a circumflex (^). To include a close bracket in the set, make it the first character after the open bracket or the circumflex; any other position will end the set. The hyphen character – is also special; when placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make it the last character before the final close bracket. For instance, [^]0-9-] means the set “everything except close bracket, zero through nine, and hyphen”. The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out.

Example: scanf(“%[a-c]”, buffer) would only extract the characters that are a, b, and c until a character that isn’t a, b, or c is found.

I’ve never heard this mentioned anywhere, so I thought I’d share this finding. Sadly this is still very primitive compared to regex. Anyways, hopefully we can in the near future move away from scanf and towards better functions.


Written by jonathanasdf

January 27, 2011 at 11:38 PM

Posted in C++

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s