c编程:停止无限循环

时间:2013-12-15 00:50:39

标签: c validation

我一直在试图验证代码,a.k.a阻止程序破坏并进入无限循环,但我觉得很难。

到目前为止,我遇到了程序中的多个点,如果用户输入字母或符号而不是程序进入无限循环的数字,用户可以通过输入错误的输入来打破它,例如主菜单所以验证的基本指南会有所帮助。

#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;
                    }
                    }
 }

1 个答案:

答案 0 :(得分:1)

scanf返回成功扫描的参数数量。

检查输入是否正确并拒绝错误输入可以简单如下:

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

然而,这不是很强大,而且验证用户输入之类的东西应该非常强大。假设用户总是输入错误的输入......这很可悲但却是真的。