gpt4 book ai didi

C语言编程: stopping endless loops

转载 作者:行者123 更新时间:2023-11-30 15:41:12 25 4
gpt4 key购买 nike

我一直在努力验证代码,也就是阻止程序中断并进入无限循环,但我发现这非常困难。

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

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

最佳答案

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

检查正确的输入并拒绝错误的输入可以很简单:

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

然而,这不是很稳健,而验证用户输入之类的东西应该非常稳健。假设用户总是会输入错误的输入......这很悲伤,但却是事实。

关于C语言编程: stopping endless loops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20590036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com