c 编程 scanf 有线行为

标签 c scanf

我从书上复制了代码,这是一个像打击一样的循环,

for(;;)
{
    printf("enter a value");
    scanf("%lf",&value);
    tot al+=value;
    ++count;
    printf("do you want to enter another value?(N or Y):");
    scanf("%c",&answer);
    if(tolower(answer)=='n')
        break;
}

但它有一些奇怪的行为,当我评估它时,它给出了输出

[tintin@tintin-laptop Documents]$ ./test 
this enter a value3
do you want to enter another value?(N or Y):enter a value

我仔细检查了一下,终于什么时候改了

scanf("%c",&answer);

%c 之前有一个空格

scanf(" %c",&answer);

它的正常表现就像

[tintin@tintin-laptop Documents]$ ./test
this enter a value2
do you want to enter another value?(N or Y):y
enter a value3
do you want to enter another value?(N or Y):

为什么会发生这种事?

最佳答案

您被输入流中留下的换行符击中。

格式字符串中的前导空格将确保 scanf() 忽略所有空格。因此,后一个版本可以按预期工作。

您可以在scanf()的手册上找到此信息。 :

A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.

关于c 编程 scanf 有线行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19252531/

相关文章:

c - 符号表中函数的 "size"到底是什么?

将字符串转换为 key_t

用于游戏服务器的 C++ MySQL

C scanf奇怪的行为

c++ - 如何从主类中调用 C++ 中的函数?

c++ - 使用 strncpy 的 ofstream 中的垃圾值

代码从 C 文本文件中读取几行

c - 扫描未知字符集

c - `scanf("%19[^\n]s",str) ;` and ` scanf ("%19[^\n]",str) 之间的差异;`

C 全局结构