c language scanf ()% c question reads delimiter

Mainly for "% c": no default separator character (including all whitespace characters) [cy teacher said wrong]

I.

    char a,b;
    scanf("%c%c",&a,&b);
    printf("%c%c",a,b);

Is no delimiter character input

Scenario 2

    char a,b;
    scanf("%c %c",&a,&b);
    printf("%c%c",a,b);

Special: the emergence of any blank characters as long as between scanf () characters% c, then the input of any blank characters (and not the number) are used as a separator similar to the situation at this time is { "% d% d" of , read intelligently identify "real" character} - but! The new round of the first character will continue to be a carriage return

In summary, after reading the plurality of character input better use of two

  • Approach to buffer the extra garbage characters

(1) Clear Buffer - have named fflush (stdin) function can be used to empty the buffer.

while(scanf("%c%c",&a,&b)!=EOF)  
    {  
        printf("a=%c,b=%c\n",a,b);  
        fflush(stdin);  
        printf("Input the value of a and b:");  
    }  

Namely: before the white characters are misreading the buffer temporarily empty.
(2) error induced by the read out data buffer (buffer indirect cleaning) - getchar () or gets ( )

For getchar (): read the first character buffer (EOF), the function returns a value of the character (EOF == - 1) (if returned to an integer variable is the ASCII code corresponding to it) extended Brothers function putchar (): putchar (ch / int) - this function output terminal to the parameter ch / int (ASCII code) corresponding to char value
for gets (): Get string (read line things)

Published 10 original articles · won praise 0 · Views 112

Guess you like

Origin blog.csdn.net/weixin_45076393/article/details/104466147