Code Tricks: Strings of words with scanf

One of the caveats of scanf and strings is that they only read characters up until the next space encountered. To read a full sentence of characters, you often have to use fgets. However, there is another way of reading strings with blank characters: the %[..] specifier, which reads a string of words. The use of %[c] means that only the characters specified within the brackets (c) are permissible in the input string. If the input string contains any other characters, the string is terminated at the first instance of the character. The specifier %[^c] does the reverse. For example:

char sentence[80];
scanf(“%[^\n]”, sentence);

This will read all the characters in a sentence until a newline is encountered, effectively storing a whole sentence including spaces and storing it in the string sentence.

Advertisements
Posted in: C

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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