0

我有一个用于模拟数据包的结构,如下所示:

typedef struct{
int source;
int dest;
int type;
int port;
char data[50];
}test;

test packet[50];

我正在尝试将数据字段中的任何内容打印到屏幕上。我当前的代码如下所示:

 printf("Enter a series of data numbers from 1-50: ");
    scanf("%c", &packet[i].data[i]);

    while (packet[i].data[i]  > 48 || packet[i].data[i] > 57)
        {
        printf("Data series needs to be between 1-50, try again: ");
        scanf("%c", &packet[i].data[i]);
        }
   printf("%c \n", packet[i].data[i]);

通过玩弄它,我已经能够编译它 - 有时它会给我 402018,有时是 X,有时只是完全跳过代码。

谁能看到我哪里出错了?我想在 packet[i] 的当前实例中打印出整个 char 数组(每次创建数据包时都会递增)

while 语句是为了确保输入的字符是一个数字,并且根据 ASCII,数字在所说的范围内。

请对我温柔一点,我对此很陌生。

非常感谢。

4

2 回答 2

0

这在逻辑上是不正确的:

while (packet[i].data[i]  > 48 || packet[i].data[i] > 57)
                          ^^                        ^^

将第>一个更改为<.

此外,您正在写入第 i 个数组成员的第 i 个数据索引,这在逻辑上再次看起来不正确。您需要维护两个循环,一个循环遍历数据包,并且对于每个数据包,内部循环将数据读入数据数组。

于 2012-05-04T15:32:49.623 回答
0

您必须使用不同的循环变量来输入该特定数据包的数组。现在,您对数据包索引和字符数组索引使用相同的变量,即“i”,而不是“scanf”,我建议对单个字符输入使用“getche()”函数。

并将您的 while 条件更改为:

 while (packet[i].data[x]  >= 48 || packet[i].data[x] <= 57)

其中“x”是附加循环变量。

for(i=0;i<=49;i++)
    printf("Enter a series of data numbers from 1-50: ");
    for(x=0;x<=49;x++){
        packet[i].data[x] = getche();
         printf("%c \n", packet[i].data[x]);
        if(packet[i].data[x]  >= 48 || packet[i].data[x] <= 57)
            {
            printf("Data series needs to be between 1-50, try again: ");
            packet[i].data[x] = getche();

            }
else
{
  break;
}

    }
于 2012-05-04T15:32:20.760 回答