![](/img/trans.png)
[英]if my scanf variable is a float and a user inputs a character how can i prompt them to input a number? assuming the scanf is inside a do while loop
[英]scanf inside an If statement on a do while loop messes up the inputs
當輸入為負數 integer 時,程序應詢問是否要重置。
當我用負數 integer 測試它時它工作正常。但是當我嘗試正數 integer 時,它不起作用(我必須輸入兩次)。
int main(void) {
int user_input;
char check;
do
{
printf("Enter a positive integer: ");
scanf("%d", &user_input);
if (user_input < 0)
printf("Error. Do you want to continue using the program? y/n: ");
scanf(" %c", &check);
} while (check == 'y');
return 0;
}
您對scanf
的第二次調用應該在方括號內,否則它不是 if 語句的一部分。 與 Python 等語言不同,縮進無關緊要。
無論用戶輸入如何,您的代碼始終執行scanf(" %c", &check)
。
int main(void) {
int user_input;
char check;
do
{
printf("Enter a positive integer: ");
scanf("%d", &user_input);
if (user_input < 0) {
printf("Error. Do you want to continue using the program? y/n: ");
scanf(" %c", &check);
}
} while (check == 'y');
return 0;
}
以下塊是相同的:
if (something)
statementA;
statementB;
if (something)
statementA;
statementB;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.