C Program#132 – Permitting & Restricting Characters in Input of Strings.

  • Permitting & Restricting Characters in Input of Strings:
    • Format Specifier %s doesn’t permit spaces between strings and stop further reading upon encountering any white space.
    • Instead, Format Specifier %[…] and %[^…] can be used respectively for permitting & restricting characters in input of strings.
    • scanf() function leaves extra character ‘\n‘ in input stream usually when, after input of string Enter Key is pressed.
    • scanf() function also leaves all those characters in input stream, which are typed in after an invalid character input & it stopped reading.
    • That remaining character ‘\n’ causes to skip next input statement (if any).
    • Other remaining characters may also skip next input statement as they are read and stored those characters as input for that next variable.
    • There are following solutions used to deal with those extra character(s)-


      • Sol. 1 – Put either a space before %c in the next input call of scanf(), such as scanf(” %c”); but only eats one extra character.
      • Sol. 2 – Use input data Suppression character (*) before next input such as scanf(“%s %* %c”,name,ch).
      • Sol. 3 – fflush(0) or fflush(stdin) are mostly used and may works on certain compilers but not all since fflush() is specifically defined to flush output buffer stdout not for stdin. Thus, may lead to unpredictable or disastrous behavior.
      • Sol. 4 – (Best Recommended Solution) is to write code below to eat extra character(s)-

        while ((ch = getchar()) != '\n' && ch != EOF) { }; //Eat Extra character(s)

        It works perfectly fine for eating extra character(s) read by getchar() function either single or multiple until ‘\n’ or EOF.

    Format Specifier Syntax- %[…] :

    Conversion Character (%) is followed by square brackets [….] within which place the character(s) or range of characters using hyphen (-) separated by commas, which you want to permit in input as valid characters.




    Format Specifier Syntax- %[^…] :

    Conversion Character (%) is followed by square brackets [….] within which place first place circumflex or caret symbol (^) , than place the character(s) or range of characters using hyphen (-) separated by commas, which you want to restrict in input as valid characters.

    Here is the well commented, self-described example program with output below:

    Following is the output of the program: