我正在寫一個小程序,輸入由3個字母組成的國名和奧運會上該國贏得的獎牌數量,程序將不斷詢問輸入,除非輸入「結束」一詞。我寫了一個while循環來做到這一點,但是我似乎無法停止卡在c程序如何在進程中停止scanf
//Program calculate the winner of olympics based on metal input
#include<stdio.h>
#include<string.h>
int main (void)
{
int maxMedals=0, tempGold=0, tempSilver=0, tempBronze=0,tempSum;
char country[3];
char winner[3];
printf("\no o o O L Y M P I C o o o");
printf("\n o o S C O R E S o o\n");
printf("Enter country code, # gold, # silver, # bronze\n");
while ((strcmp(country,"end"))!=0)
{
printf("==>");
scanf("%s %d %d %d",&country, &tempGold, &tempSilver, &tempBronze);
tempSum=tempGold+tempSilver+tempBronze;
if (maxMedals<tempSum)
{
maxMedals = tempSum;
strcpy(winner, country);
// printf("\n %s", winner);
}
else
{
maxMedals=maxMedals;
}
}
printf("\nwe reached here\n");
printf("\nWinner is %s with %d medals\n", country, maxMedals);
return 0;
}
在這個程序的情況下,即使在我輸入結尾時它也不會停止,因爲它仍然會要求3個額外的整數輸入作爲分數,無論如何,當它檢測到該單詞時「scan short」scanf 「end」已輸入 – nanobots
您必須使用單獨的'scanfs'而不是'fgets'來獲取國家/地區。 – Rohan
@ user2948725只需在'country'之前刪除'&',那麼每件事都可以。 –