【问题标题】:How to use char in scanf by using loop?如何使用循环在scanf中使用char?
【发布时间】:2021-02-04 06:57:02
【问题描述】:

我想做简单的计费软件,但不知道如何解决这个问题

#include <stdio.h>
    
int main()
{
    char a[20];
    int i, j, b;
    i = 0;
    printf("How many item you have?\n>>> ");
    scanf("%d", &j);
    for (int i = 0; i < j; i++)
    {
        
        printf("Type the name of item no. %d?\n>>> ", i + 1);
        scanf("%c", &a);
        printf("Type the item quantity?\n>>> ");
        scanf("%d", &b);
    }
        
    return 0;
}

如您所见,此代码仅用于提问。在这段代码中一切都很好,但是当我运行这段代码时,输​​出是:

How many item you have?
>>> 4
Type the name of item no. 1?
>>> Type the item quantity?
>>>

一切似乎都很好,但我没有输入项目名称,循环直接询问第二个问题。这怎么可能?

【问题讨论】:

  • 当您按下 Enter 键以获取项目计数(j 的输入)时,它会作为换行符添加到输入缓冲区中。然后,下一个scanf 调用会读取此换行符,以输入a。这是一个非常常见的初学者问题,如果您稍微搜索一下,您应该很容易找到解决方法。
  • scanf("%c", &amp;a); 这只会读取 1 char,而不是名称。请改用%19s。当然,永远不要在不检查返回值的情况下使用scanf
  • 再看源码,看来你要读入a的是一个字符串,而不是单个字符。同样,您应该能够很容易地找到它,因为任何体面的书籍或教程或课程都应该告诉您如何使用scanf 来读取字符串。
  • 在另一个但不相关的注释中,请不要对变量使用简单的单字母名称。使用描述其用途的内容,例如 name 而不是 a。这将使您的代码更加更易于阅读和理解。

标签: c char scanf billing


【解决方案1】:

scanf%c 格式说明符读取 单个 字符。要读取字符串(数组),请使用%s 格式说明符。此外,对于此类数组,您不需要 &amp;(地址)运算符,因为数组名称本身将“衰减”为指向其第一个元素的指针:

#include <stdio.h>

int main()
{
    char a[20];
    int i, j, b;
    i = 0;
    printf("How many item you have?\n>>> ");
    scanf("%d", &j);
    for (int i = 0; i < j; i++) {
        printf("Type the name of item no. %d?\n>>> ", i + 1);
        scanf("%19s", a); // The "19" limits input size and allows space for the nul-terminator
        printf("Type the item quantity?\n>>> ");
        scanf("%d", &b);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 2015-11-26
    • 2023-03-07
    • 1970-01-01
    • 2012-05-14
    • 2013-12-28
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多