這是一個簡單的C代碼:
#include <stdio.h>
int main()
{
char choice;
int condition = 0;
while (condition < 3)
{
printf("Type in a number: ");
scanf("%hhd", &choice);
condition ;
printf("%d\n", condition);
}
}
我希望condition每次輸入字符時都會增加我的變數。但突然間輸出看起來像這樣:
Type in a number: 1
1
Type in a number: 2
1
Type in a number: 3
1
Type in a number: 4
1
Type in a number: 5
1
Type in a number: 6
1
Type in a number: 7
1
Type in a number:
如果我注釋掉,問題就會消失scanf("%hhd", &choice);。怎么會這樣?一個錯誤?我gcc 8.1.0通過mingw-w64。
一切都很好用clang,我只是想知道為什么它是這樣的gcc。
我已將其void作為引數放置main并解決了問題。為什么?
uj5u.com熱心網友回復:
您不能使用 %hhd 來獲取字符。
你應該使用int choice;或scanf("%c", &choice);
uj5u.com熱心網友回復:
看起來您的 C 庫可能沒有正確實作說明%hhd符scanf。
我在我的機器上嘗試了這個測驗片段:
char a[] = "abcdef";
scanf("%hhd", &a[3]);
我輸入了88,字串變成了abcXef,確認只%hhd寫入了一個位元組的記憶體,正如預期的那樣。
我沒有看到您發布的代碼有任何明顯錯誤。在我的機器上,它只提示三個輸入,因為condition變數正確遞增。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364023.html
上一篇:在檔案中查找特定位元組
