2013-12-15 97 views
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; 
        } 
        } 
} 
+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; 
} 

这不是很强劲,但是,像验证用户输入应该是非常稳健的。假设用户总是输入错误的输入......这很可悲,但却是真实的。