我寫了一個投票箱的簡單代碼,它應該只在投票者數量大于或等于 31 時才開始投票。但是,當我插入任何以 0 開頭的值時,比如 04,它會將投票者更改為 0。
我需要使用這樣的值作為輸入,因為它是有問題的。04代表總統,08代表另一位,00代表沒有。
另外,我使用總統作為字串,因為我讀到以 0 開頭的數字被讀為八進制。
在總統中輸入一個值時,我可以對選民數量做些什么?
int main() {
int option, voters = 0, i = 0;
char president[2];
setlocale(LC_ALL,"");
do {
printf("Options\n1 - Insert amount of voters\n2 - Start voting\n3 - Leave\nChoose: ");
scanf("%i", &option);
while (option <= 0 || option >= 4) {
printf("This option doesn't exist, try again: ");
scanf("%i", &option);
}
switch (option) {
case 1:
system("cls");
printf("Amount of voters: ");
scanf("%i", &voters);
break;
case 2:
system("cls");
if (voters <= 30) {
printf("There isn't enough voters. Returning to main menu...");
break;
} else {
for (i = 1; i <= voters; i ) {
printf("Insert president vote: ");
scanf("%s", president);
}
}
break;
}
} while (option != 4);
return 0;
}
uj5u.com熱心網友回復:
問題scanf("%s", president);在于你定義president為char president[2];which 意味著president只包含兩個字符。
為什么這是一個問題?
好吧,因為scanf從控制臺獲取字串時會自動在末尾添加一個空字符,這意味著當您輸入時04,scanf將存盤"0\0"到president.
如何解決?
只是將其擴展char president[2];為char president[3];
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335256.html
標籤:C
上一篇:再現C函式的功能
下一篇:保護不透明資料型別的資料
