0
我一直在試圖讓我的頭在驗證代碼,a.k.a停止程序打破並進入無限循環,但我覺得很難。c編程:停止無限循環
到目前爲止,我遇到過程中的多個點,如果用戶輸入字母或符號而不是數字,則用戶可以通過在主菜單中輸入錯誤的輸入來打破它,程序進入無限循環,所以關於驗證的基本指南將會有所幫助。
#include <stdio.h>
#include <stdlib.h>
struct packet{
int source;
int destination;
int type;
int port;
char data[50];
};
void main()
{
struct packet s[50]; //Array for structure input
int choice;
int customerCount = 0, ii = 0;
while (customerCount <= 50){
printf("What would you like to do?\n");
printf("\t1) Add a packet.\n");
printf("\t2) s all packets.\n");
printf("\t3) Save packets.\n");
printf("\t4) Clear all packets.\n");
printf("\t5) Quit the programme.\n");
scanf("%i", &choice);
switch (choice)
{
case 1: printf("\n****Adding a packet*****\n");
printf("Where is the packet from?\n");
scanf("%i", &s[customerCount].source);
printf("Where is the packet going?\n");
scanf("%i", &s[customerCount].destination);
printf("What type is the packet?\n");
scanf("%i", &s[customerCount].type);
printf("What is the packet's port?\n");
scanf("%i", &s[customerCount].port);
printf("Enter up to 50 characters of data.\n");
scanf("%s", s[customerCount].data);
customerCount++;
break;
case 2: printf("\nDisplaying Infomation\n");
for(ii = 0; ii < customerCount; ii++) {
printf("\nSource: %d", s[ii].source);
printf("\nDestination: %d", s[ii].destination);
printf("\nType : %d", s[ii].type);
printf("\nPort : %d", s[ii].port);
printf("\nData: %s\n---\n", s[ii].data);
}
break;
case 3: break;
case 4: break;
case 5: break;
default: printf("\nThis is not a valid choice, please choose again\n\n");
break;
}
}
}
這裏有什麼問題? – bmargulies
'scanf'返回成功轉換的參數個數。您必須檢查所有數字轉換是否爲1,否則循環提示並重新掃描,直到它爲止。這個邏輯可以放在一個單獨的函數中,所以不需要重複。 – Gene
在第二段中,我問了如何在輸入字母時解決無限循環的問題 –