簡體   English   中英

如何確保我的輸入字符串只有字符且不超過 10 個字母?

[英]How can I make sure my input string has only characters & is 10 letters or less?

我目前正在為分配編寫代碼,我正在嘗試對這段代碼進行錯誤檢查,以便當用戶給出輸入字符串時,如果它超過 10 個字符或包含數字,它將循環直到有效輸入給。 (有效為 10 個字符或更少。)這是我目前所擁有的。 我目前無法拍攝 STRING 部分。 (STRING 定義為 10)

#define STRING 10

typedef struct
{
    char make[STRING];
    Date manufactureDate;
    Date purchaseDate;
    double purchasePrice;
}Car; 

void addCar(Car *carIn)
{
    do
    {
        printf( "\n Enter the make: ");
        scanf("%s", (*carIn).make);
    }while((*carIn).make) strlen(10));

    printf( "Manufacture date > (DD/MM/YYYY) \n");
    getDate(&(*carIn).manufactureDate);
    printf( "Purchase date > (DD/MM/YYYY) \n");
    getDate(&(*carIn).purchaseDate);

    do
    {
       printf( " Enter the purchase price (100.00 = $100.00): ");
       scanf("%lf", &(*carIn).purchasePrice);
    }while ((*carIn).purchasePrice <= 0);
}

在編輯問題和擴展addCar()函數之前開始回答。

假設您有以下結構定義:

typedef struct Car Car;
struct Car
{
    …
    char make[11];
    …
};

然后你可以編寫代碼,而不是:

void addCar(Car *carIn)
{
    while (printf("\nEnter the make: ") > 0 &&
           scanf("%10[A-Za-z]", carIn->make) != 1)
    {
        printf("Did not recognize that!\n");
        int c;
        /* Didn't get any alpha characters - read the line and start over */
        while ((c = getchar()) != EOF && c != '\n')
            ;
        if (c == EOF)
        {
            printf("Farewell!\n");
            exit(1);
        }
    }
}

請注意,您的蘭博基尼車主不會對您滿意。

還要注意-> (箭頭)運算符的使用; 它旨在使(*carIn).make不必要。 當結構指針嵌套在其他結構中時,它極大地簡化了表示法。 比較(*(*s1).s2).members1->s2->member

暫無
暫無

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

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