c - 三个 scanf 导致两个并获取垃圾值

标签 c char scanf

这是基本结构的代码,但输出不符合预期。有三个 scanf 函数,但只有两个正在执行。中间一个包含垃圾值。

#include <stdio.h>

int main()
{
    struct book
    {
        char name;
        float price;
        int pages;
    };

    struct book b1,b2,b3;

    printf("Enter names , prices & no of pages of 3 books\n");
    scanf("%c%f%d",&b1.name,&b1.price,&b1.pages);
    scanf("%c%f%d",&b2.name,&b2.price,&b2.pages);
    scanf("%c%f%d",&b3.name,&b3.price,&b3.pages);

    printf("And this is what you entered\n");
    printf("%c%f%d",b1.name,b1.price,b1.pages);
    printf("%c%f%d",b2.name,b2.price,b2.pages);
    printf("%c%f%d",b3.name,b3.price,b3.pages);

    return 0;
}

最佳答案

简单地改变

scanf("%c%f%d", &bx.name, &bx.price, &bx.pages);

scanf(" %c%f%d", &b1.name, &b1.price, &b1.pages);

Enter后,stdin中会留下一个“\n”,稍后将被“%c”消耗。读取字符 ('\n') 后,scanf() 需要一个 float ,如格式字符串中的“%f”所示。然而,它没有得到所需的 float ,而是遇到了一个字符,然后悲伤地返回了。因此,&bx.price&bx.pages 不会更新,因此它们保持未初始化状态,为您提供垃圾值。

如果 scanf() 中存在前导空格,则在读取开始之前将丢弃所有空白字符(如果有)。由于\n被丢弃,接下来的读取过程将(大概)成功。

另外,还有一个提示:始终检查 scanf() 的返回值,因为您永远不知道用户将输入什么内容。

示例代码:

#include <stdio.h>

struct book
{
    char name;
    float price;
    int pages;
};

int main()
{
    struct book b1, b2, ..., bx;

    printf("Enter names, prices & no of pages of x books:\n");
    while (scanf(" %c%f%d", &bx.name, &bx.price, &bx.pages) != 3)
    { 
        fputs("Error reading bx. Please try again:\n", stderr);
        scanf("%*[^\n] ");
    }
    ......

    printf("And this is what you have entered:\n");
    printf("%c %f %d", bx.name, bx.price, bx.pages);
    ......

    return 0;
}

输入和输出示例:

Enter names, prices & no of pages of x books:
asd wedewc efcew
Error reading bx. Please try again:
a 12.34 42
And this is what you have entered:
a 12.340000 42

关于c - 三个 scanf 导致两个并获取垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113511/

相关文章:

c - 为什么在任意内存位置设置值不起作用?

c - int LA[] = {1,2,3,4,5} c 中的内存分配困惑

c - 在 RPCGen 中将字符指针从客户端传递到服务器

c - fscanf 返回错误的数字

c - fscanf返回值和链表

c - 如何从标准输入打印行?

c - C 中的单线程与 pthread 的多线程

c - 从类似图像的数据网格中提取简单形状的列表

c - 如何获取用户输入的字符?

c - 整数到字符串转换器(使用宏)