我的代码有效,但打印不正确。这是我的输入:
请输入 1 表示字符,2 表示整数,3 表示浮点数,4 表示单词
1 abcdefghijklmnop 3 123.4 45.54 6.0 7890.09876 2 123 34 23 12345 4 aaaaa bbbbb ccccc sssssssssssssssssss
我不知道如何让它像它应该的那样在 cccccc 之后停止。在它通过之前,我必须输入随机的东西来填满空间。我很确定这与不使用malloc有关。
然后这是输出:
类型 1:abcdefghijklmnop 类型 3:123.400002/ 45.540001/ 6.000000/ 7890.098633 类型 2:123、34、23、12345 类型 4:ccccc ccccc ccccc 类型 1:ssssssssssssss
在类型 4 上,它应该是 aaaaa bbbbb ccccc,但它却是这样做的。并且在类型 1 上,它没有显示,但它打印出来就像这个奇怪的方形故障一样。
这是我的代码。它在 3 个文件中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lab5.h"
#include "lab5dispatch.c"
#define MAX_ENTRIES 16
int main()
{
MESSAGE cache[MAX_ENTRIES];
int i = 0;
printf("Please enter in 1 for characters, 2 for ints, 3 for floats and 4 for words\n");
while (scanf("%d", &cache[i].messageType) != EOF && i < MAX_ENTRIES)
{
switch(cache[i].messageType)
{
case 1:
scanf("%16s", &cache[i].MESSAGE_CONTENT.charPointer);
break;
case 2:
scanf("%d", &cache[i].MESSAGE_CONTENT.theInts[0]);
scanf("%d", &cache[i].MESSAGE_CONTENT.theInts[1]);
scanf("%d", &cache[i].MESSAGE_CONTENT.theInts[2]);
scanf("%d", &cache[i].MESSAGE_CONTENT.theInts[3]);
break;
case 3:
scanf("%f", &cache[i].MESSAGE_CONTENT.theFloats[0]);
scanf("%f", &cache[i].MESSAGE_CONTENT.theFloats[1]);
scanf("%f", &cache[i].MESSAGE_CONTENT.theFloats[2]);
scanf("%f", &cache[i].MESSAGE_CONTENT.theFloats[3]);
break;
case 4:
scanf("%s", &cache[i].MESSAGE_CONTENT.word1);
scanf("%s", &cache[i].MESSAGE_CONTENT.word2);
scanf("%s", &cache[i].MESSAGE_CONTENT.word3);
break;
}
i++;
}
message_dispatcher(cache, i);
}
这是第二个文件。
#ifndef LAB5_H_ /* to prevent re-definitions */
#define LAB5_H_ /* that cause errors */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//the unsigned short is to store what type of data the main struct will store
typedef struct MESSAGE
{
unsigned short int messageType;
union
{
char * charPointer; //this is for the string
int theInts[4];
float theFloats[4];
char word1[5]; //can probably use a 2d array here but that's too complicated right now haha
char word2[5];
char word3[5];
} MESSAGE_CONTENT;
} MESSAGE;
这是最后一个文件。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lab5.h"
void message_dispatcher( MESSAGE msg[], int j ) {
int i;
for (i = 0; i < j; i++)
{
switch(msg[i].messageType)
{
case 1:
printf("Type 1: %s\n", &msg[i].MESSAGE_CONTENT.charPointer);
break;
case 2:
printf("Type 2: %d, %d, %d, %d\n", msg[i].MESSAGE_CONTENT.theInts[0],
msg[i].MESSAGE_CONTENT.theInts[1], msg[i].MESSAGE_CONTENT.theInts[2],
msg[i].MESSAGE_CONTENT.theInts[3]);
break;
case 3:
printf("Type 3: %f/ %f/ %f/ %f \n", msg[i].MESSAGE_CONTENT.theFloats[0], msg[i].MESSAGE_CONTENT.theFloats[1], msg[i].MESSAGE_CONTENT.theFloats[2], msg[i].MESSAGE_CONTENT.theFloats[3]);
break;
case 4:
printf("Type 4: %s %s %s\n", msg[i].MESSAGE_CONTENT.word1, msg[i].MESSAGE_CONTENT.word2, msg[i].MESSAGE_CONTENT.word3);
break;
}
}
}