Continuous use in the C language scanf () function emerging issues

 

#include<stdio.h>
 
int main()
{
    char string_c[20],*c;
    printf("input string:\n");
    scanf("%c",string_c);
    printf("input a char:\n");
    scanf("%c",c);
    pritnf("%s  %c",string_c,*c);
    return 0;
}

 

This situation such as the above error occurs, when the program is run when the input character string occurs after the second time does not need to input characters, which directly results. In fact, a carriage return after the first input string, the last '\ n' did not give String_c, but stored in the cache, the second time when the need to enter directly to the cache character assignment.

Solution:

(1) The two scanf () function is written as a sancf ( "% s% c", striing_c, c);

(2) In the first scanf () function below flush the cache write operation: fflush (stdin) Refreshing the input buffer

(3) In the first scanf () function added getchar () , the '\ n' taken directly, it does not act

(4) in a scanf () function so write: scanf ( "% c \ n", string_c)

 

 

 


Original link: https: //blog.csdn.net/PyDongJava/article/details/84572002

 

#include<stdio.h>
int main()
{
 char ch1,ch2;
 printf("Input for ch1:/n");
 scanf("%c",&ch1);
 printf("ch1=%c/n",ch1);
 printf("Input for ch2:/n");
 scanf("%c",&ch2);
 printf("ch2=%c/n",ch2);
}

 

On the surface this procedure is not wrong, it can run, but during the operation to a second scanf input values ​​to ch2, the program will not stop, but run directly to the last printf!

   why? I was baffled. . .

   Today checked the Internet to know the original scanf is read from the standard data input buffer input, and the input format% c character receives a carriage return character, press Enter after entering characters in the input end of the first scanf when the saved carriage return, the second face scanf input buffer, it is automatically assigned to the carriage return to the ch2. And if the second scanf input format% c is not the time, because they do not match the format, the carriage return will automatically be ignored, thus giving rise to such a problem when Liangge% c format only continuous input!

   Solution :( two ways to choose one)

   1. Empty input buffer

   Was added after the first sentence scanf: fflush (stdin); // C language function input buffer empty

   2. Format added space control

   The second read scanf: scanf ( "% c", & ch2); // add a space before the number%

Requires exactly the same format as the input character when the control inputs of scanf (eg: scanf ( "abcd% c", & ch); abcde input must be entered, ch obtained is e) can be offset by the transport space previously entered symbol.

Original link: https://www.cnblogs.com/GoldCrop/p/11306547.html

 

Guess you like

Origin www.cnblogs.com/jasonLiu2018/p/11520918.html