Use scanf() function with a scanset - C Language Basics

C examples for Language Basics:scanf

Introduction

The scanf( ) function can have a scanset, which defines a set of characters to be read by the scanf().

You define a scanset by putting the characters inside square brackets.

For example, the following scanset tells scanf( ) to read only the characters X, Y, and Z:

%[XYZ]

When using a scanset, scanf( ) continues to read characters until it encounters a character outside the scanset.

To specify an inverted set, append ^ in front of the set. ^ tells scanf( ) to read characters that are not in the scanset.

To specify a range in the scan set, use a hyphen. For example, this tells scanf( ) to accept the characters A through Z:

%[A-Z]

The scanset is case sensitive. To scan for both upper- and lowercase letters, you must specify them individually.

To see how this works, try this program:

Demo Code

#include <stdio.h>

int main(void)
{
   int i;// ww  w.j  av  a  2  s .  c o  m
   char str[80], str2[80];

   printf("testing the scanf scan set. %[abcdefg] \n");

   scanf("%d%[abcdefg]%s", &i, str, str2);
   printf("%d %s %s", i, str, str2);

   return 0;
}

Result


Related Tutorials