2013-12-15 4 views
0

코드 유효성 검사를 끝내고 무한 루프를 중단하고 입력하는 프로그램을 중지하는 데 머리를 쓰려고했지만 꽤 어려웠습니다.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; 
        } 
        } 
} 
+0

여기에 질문이 무엇입니까? – bmargulies

+0

'scanf'는 성공적으로 변환 된 인자의 수를 반환합니다. 모든 숫자 변환에 대해 1이라는 것을 확인하고 그렇지 않은 경우 루프 할 때까지 다시 묻고 다시 스캔하십시오. 이 논리는 별도의 기능에 배치 할 수 있으므로 반복 할 필요가 없습니다. – Gene

+0

두 번째 단락에서 나는 편지를 입력 할 때 무한 루프와 함께 문제를 어떻게 해결할 것인지 질문했다. –

답변

1

scanf이 성공적으로 스캔 된 인수의 수를 반환합니다. 적절한 입력을 확인하고 잘못된 입력을 거부하는 것은 간단 할 수

:

printf("Where is the packet from?\n"); 
while(scanf("%i", &s[customerCount].source) != 1) 
{ 
    while(getchar() != '\n') 
     continue; 
} 

이 그러나, 매우 강력하고, 사용자 입력의 유효성을 검사 같은 것을 매우 강력해야한다. 사용자가 항상 잘못된 입력을 입력한다고 가정합니다 ... 슬프지만 사실입니다.