c - 当指定的格式是字符时接受字符串

标签 c string char scanf

我有以下代码。我想我应该一次只输入一个字符。但即使我在一行中输入像 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/

相关文章:

c - C 正则表达式支持前瞻吗?

c - C/Objective-C 中的 ANSI 颜色提取库

java - 如何解析作为字符串给出的数学表达式并返回一个数字?

将一维字符串数组转换为c中的二维字符串数组

java - Java 方法中的整数输出与预转换的 char 值不同

c - msgrcv - SA_RESTART 标志不起作用

java - ConcurrentHashMap 中 String intern 方法的去重

C指针char到小写

java - 如何在Java中将用户输入的字符与字典文件进行比较?

c - 使用静态常量结构来限制 C 中常量的名称冲突有什么问题吗?