问题指出,如果在scanf后跟fgets()
/ gets()/ scanf(),它将是有效的内容或输出内容。
scanf()
#include<stdio.h> int main() { int x; char str[100]; scanf("%d", &x); fgets(str, 100, stdin); printf("x = %d, str = %s", x, str); return 0; }
输出结果
Input: 30 String Output: x = 30, str =
说明
fgets()和gets()
用于在运行时从用户获取字符串输入。我上面的代码在运行时输入整数值,则它不会采用字符串值,因为当我们在整数值之后输入换行符时,则fgets()
或gets()
将采用换行符作为输入,而不是所需的输入“ String”。
scanf()
要反复scanf()
跟随a,scanf()
我们可以使用循环。
#include<stdio.h> int main() { int a; printf("enter q to quit"); do { printf("\nenter a character and q to exit"); scanf("%c", &a); printf("%c\n", a); }while (a != ‘q’); return 0; }
输出结果
Input: abq Output: enter q to quit enter a character and q to exita a enter a character and q to exit enter a character and q to exitb b enter a character and q to exit enter a character and q to exitq
说明
在这里,我们可以看到在额外的新行之后有额外的行“输入一个字符并q退出”,这是因为每次scanf()
将一个换行符都留在缓冲区中,scanf()
随后他将读取该行。为了解决这个问题,在scanf()
scanf(“%c \ n”)之类的类型说明符中使用'\ n' ;或另一个选择是我们可以使用多余的getchar()
或scanf()
读取多余的新行。