我有以下代码。我想我应该一次只输入一个字符。但即使我在一行中输入像 hello 这样的字符串,它也会正确接受。为什么是这样?是否与标准输入缓冲区刷新问题有关?
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
int main()
{
char sourceString [100];
int index=0;
printf("Enter the characters one by one enter * to stop\n");
do
{
scanf("%c",&sourceString[index]);
index++;
} while (sourceString[index-1]!='*');
index=0;
while (sourceString[index]!='*')
{
printf("%c",sourceString[index]);
index++;
}
printf("\n");
return(0);
}
最佳答案
当您输入字符串并按 Enter 时,整个字符串将进入输入缓冲区 stdin
。
接下来,根据 %c
格式说明符的属性,如 C11
标准第 §7.21.6.2 章中所述,fscanf( )
Matches a sequence of characters of exactly the number specified by the field width (1 if no field width is present in the directive).
它将匹配(并扫描并存储)缓冲区中的第一个条目(char
),而缓冲区内容的其余部分保持不变。
当您在循环中运行 scanf()
时,下一次调用将再次从输入缓冲区中读取(并继续,只要它们的内容在 标准输入
缓冲区)。
关于c - 当指定的格式是字符时接受字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35750154/