我的C代碼如下
int main() {
int userInput = 0;
while (userInput != 4) {
printf("Enter a number : ");
scanf("%d", &userInput);
};
return 0;
}
這通常在輸入整數值時起作用。但是當輸入一個字串值時,它不會再次詢問輸入。它進入無限回圈列印“輸入數字”短語。然后,我嘗試了如下代碼。
int main() {
int userInput = 0;
while (userInput != 4) {
userInput = 0; // reset the userInput value
printf("Enter a number : ");
scanf("%d", &userInput);
};
return 0;
}
即使那樣也沒有解決我的問題。為什么會這樣?如何修復?
uj5u.com熱心網友回復:
您需要從無效資料中釋放輸入緩沖區。類似于以下內容。
do
{
printf("Enter a number : ");
if ( scanf("%d", &userInput) != 1 )
{
scanf( "%*[^\n]" );
userInput = 0;
}
} while ( userInput != 4 );
另一種方法是使用該函式fgets讀取字符陣列中的整個字串,然后使用將其轉換為整數strtol并檢查轉換是否成功。
uj5u.com熱心網友回復:
“這通常在輸入整數值時起作用。但是當輸入字串值時,它不會再次詢問輸入。”
當您輸入的輸入與預期型別(即%dfor scanf())和int型別不匹配時userInput,輸入流(在本例中為stdin)未高級,這會導致反復嘗試從相同的錯誤輸入中轉換相同型別的資料.
此外,scanf()回傳一個值,指示成功轉換了多少項。鑒于您輸入了一個字串,但使用%d格式說明符進行掃描,零項將被轉換。檢查該值允許程式員優雅地處理不正確的用戶輸入
int num_converted = scanf("%d", &userInput);
if(num_converted != 1)
{
//handle error
...
}
順便說一句,請考慮使用fgets().
下面將整個輸入行讀入緩沖區,消除不需要的空白,然后才將清理過的緩沖區轉換為值...
int main(void) {
int userInput = 0;
char inBuf[20] = {0};
printf("Enter a number : ");
while (fgets(inBuf, sizeof inBuf, stdin)) {
inBuf[strcspn(inBuf, "\r\n")] = 0;//remove unwanted white space
userInput = atoi(inBuf);//strtol() would be an alternative
printf("\n%d entered!\n\nctrl-c to exit\n...Or enter a number : \n", userInput);
};
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359057.html
下一篇:c整數轉二進制數
