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
在第二段中,我问了如何在输入字母时解决无限循环的问题 –