3

case switch ステートメント内に if/else をネストしようとしています。大文字と小文字の「p」または「P」を入力すると、入力した文字に関係なく $15.00 の行が出力されます。出力を変更せずに {} を移動/追加しようとしました。

時間を割いて初心者を助けてくれてありがとう。

コード全体はここにあります。

#include <stdio.h>

int main()
{
//variable declarations 
char typeOfWash, tireShine;

//Menu
printf("R ---> Regular ($5.00)\n");
printf("B ---> Bronze ($7.50)\n");
printf("G ---> Gold ($10.25)\n");
printf("P ---> Platinum ($15.00)\n");
printf("Tire Shine can be added to the Gold or Platinum ONLY,");
printf("for an additional$2.50\n\n");

printf("Enter your selection: ");
scanf("%c",&typeOfWash);

switch (typeOfWash)
{
    case 'R': case 'r':
        printf("Your bill total is: $5.00\n");
        break;
    case 'B': case 'b':
        printf("Your bill total is: $7.50\n");
        break;
    case 'G': case 'g':
        printf("Would you Like a Tire Shine? (Y/N): ");
        scanf("%c ",&tireShine);
        if (tireShine == 'Y' || tireShine == 'y')
            printf("Your bill total is: $12.75\n");
        else
            printf("Your bill total is: $10.25\n");
        break;
    case 'P': case 'p':
        printf("Would you Like a Tire Shine? (Y/N): ");
        scanf("%c ",&tireShine);
        printf("%c",tireShine);
        if (tireShine == 'Y' || tireShine == 'y')
            printf("Your bill total is: $17.50\n");
        else
            printf("Your bill total is: $15.00\n");
        break;
    default:
        printf("Invalid Choice");

}
return 0;
}
4

5 に答える 5

2

問題はscanf%cフォーマット指定子を使用すると空白が消費されず、この場合\n、入力バッファーに残されることです。インストラクターが提案しているように見えるのは、最初の入力の末尾の空白を次の入力で食べることscanfです。ただし、これにより問題が解決するため、末尾のスペースではなく先頭のスペースを挿入するように言われたと思われます。

scanf(" %c", &tireShine);

getchar()または、秒の直前に使用scanfして、改行文字を事前に消費することもできます。

getchar();
scanf("%c", &tireShine);

%s2 番目の方法は、代わりに書式指定子を使用し、%cそれに応じて処理することです。

getchar()入力バッファから 1 文字しか消費しないことに注意してください。たとえば、ユーザーが 1 文字を超える文字列を入力した場合while ((x = getchar()) != '\n') ;、バッファーをクリアするようなものが必要になります。

于 2012-09-26T08:56:18.527 に答える
0

これを試して::

printf("Enter your selection: ");
scanf("%c",&typeOfWash);
fflush(stdin) ;

ただし、使用は避けてください。 更新::

printf("Enter your selection: ");
scanf("%c",&typeOfWash);
getchar() ;

fflush(stdin)は未定義動作になるため、getchar ()を使用してストリームをクリアできます。

于 2012-09-26T08:42:37.387 に答える
0

場合はインラインで試してください。

case 'P': case 'p':
    printf("Would you Like a Tire Shine? (Y/N): ");
    scanf("%c",&tireShine);
    printf("Your bill total is: $%s\n", toUpper(tireShine) == 'Y' ? "17.50":"15.00");
    break;
于 2012-09-26T07:58:43.593 に答える
0

もう 1 つスペースがあります。

変化する

scanf("%c ", &tireShine);

scanf("%c", &tireShine);
于 2012-09-26T07:59:49.883 に答える
0

scanf() の 1 つの問題は、通常、「リターン」が読み取られないままになることです。したがって、'p' のようなものを入力してから 'return' を入力すると、'p' を読み取って処理しますが、'return' は処理しません。scanf() への 2 番目の呼び出しは、既にそこにあった「return」文字を読み取るため、「y」または「Y」と一致しません。ケース「g」でも同じ問題があります。「%c」または「%c」のどちらを使用してもかまいません。この問題は、行末を示す 2 つの文字を持つ DOS システムではさらに悪化する可能性があります。

于 2012-09-26T10:18:47.983 に答える