我在 Visual Studio 上用 C 語言撰寫代碼,但似乎無法解決 scanf_s 掃描一次的問題。
#include <stdio.h>
#include <string.h>
int main() {
int duration;
int cost;
printf("1 day = 50$\nFor students:\n2 days = 90$\n3 days = 120$\n");
question_1:
printf("What's your stay duration in days?\n");
scanf_s("%d", &duration);
if (duration == 1)
{
printf("That will be 50$.");
}
else
{
if (duration == 2 || duration == 3)
{
question_2:
printf("Are you a student?\n");
char answer[20];
scanf_s("%s", &answer, sizeof(answer));
if (strcmp(answer, "yes") == 0)
{
if (duration == 2)
{
printf("That will be 90$.");
}
else
{
printf("That will be 120$.");
}
}
else
{
if (strcmp(answer, "no") == 0)
{
cost = duration * 50;
printf("That will be %d$.", cost);
}
else
{
goto question_2;
}
}
}
else
{
goto question_1;
}
}
}
當輸入一個單詞而不是數字來表示“持續時間”時,程式會重復列印“你的停留時間是多少天?” 而不是掃描另一個輸入,我應該改變什么?
uj5u.com熱心網友回復:
您需要在輸入無效后清除輸入緩沖區。例如
printf("1 day = 50$\nFor students:\n2 days = 90$\n3 days = 120$\n");
question_1:;
int result;
do
{
printf("What's your stay duration in days?\n");
result = scanf_s("%d", &duration);
if ( result != 1 )
{
while ( getchar() != '\n' );
}
} while ( result != 1 );
請注意,使用回圈而不是 goto 陳述句和標簽要好得多。嘗試使用回圈重寫您的程式。
還要注意標簽后面的分號
question_1:;
問題是在 C 中你不能在宣告之前放置標簽。所以空陳述句有助于解決問題。
uj5u.com熱心網友回復:
此版本的代碼按我、發帖人和 C 新手的意圖作業。
#include <stdio.h>
#include <string.h>
int main() {
int duration;
int cost;
int check;
printf("1 day = 50$\nFor students:\n2 days = 90$\n3 days = 120$\n");
question_1:
do
{
printf("What's your stay duration in days?\n");
check = scanf_s("%d", &duration);
if (check != 1)
{
while (getchar() != '\n');
}
} while (check != 1);
if (duration == 1)
{
printf("That will be 50$.");
}
else
{
if (duration == 2 || duration == 3)
{
question_2:
printf("Are you a student?\n");
char answer[20];
scanf_s("%s", &answer, sizeof(answer));
if (strcmp(answer, "yes") == 0)
{
if (duration == 2)
{
printf("That will be 90$.");
}
else
{
printf("That will be 120$.");
}
}
else
{
if (strcmp(answer, "no") == 0)
{
cost = duration * 50;
printf("That will be %d$.", cost);
}
else
{
goto question_2;
}
}
}
else
{
goto question_1;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523655.html
標籤:C标签扫描去
下一篇:C中指向陣列的指標
