簡體   English   中英

如何使用循環在scanf中使用char?

[英]How to use char in scanf by using loop?

我想制作簡單的計費軟件,但我不知道如何解決這個問題

#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?
>>>

一切似乎都很好,但我還沒有輸入項目名稱,循環直接詢問第二個問題。 怎么可能?

scanf%c格式說明符讀取單個字符。 要讀取字符串(數組)字符,請使用%s格式說明符。 此外,對於此類數組,您不需要& (地址)運算符,因為數組名稱本身將“衰減”到指向其第一個元素的指針:

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM