我正在尝试建立一个非常基本的框架,以便在我想要制作的游戏中以程序方式生成房间描述。但是,我的描述都混乱了。我无法弄清楚原因。
以下是相关代码:
来自main.c:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "structs.h"
char RoomDesc[60];
int main()
{
RoomGen(RoomDesc);
printf("This room %s ", RoomDesc);
return 0;
}
void RoomGen(char* RoomDesc) {
srand (time(NULL));
RoomDesc[0]=0; /* Create zero length string,
make sure it's cleared out after any previous uses */
/* RoomDesc1 describes the overall appearance of a room, and RoomDesc2
is if the floor is even, upwards or downwards. "on a" is a connector. */
strcat(RoomDesc, RoomDesc1[(rand() % 5)]);
strcat(RoomDesc, "on a ");
strcat(RoomDesc, RoomDesc2[(rand() % 3)]);
}
这是structs.h:
void RoomGen(char *RoomDesc);
char RoomDesc1[30][6] = {
"is a litter filled mess",
"is strewn with bones",
"is almost empty",
"feels like there is a presence",
"feels quite warm",
"feels chilly"
};
char RoomDesc2[14][3] = {
"upward slope",
"downward slope",
"even keel"
};
输出应该如下:“这个房间在向下的斜坡上几乎是空的。”
相反,它看起来像:“这个房间感觉前夕,”(或者可能会有所不同,因为随机部分似乎正在起作用,但这就是现在的测试运行了。)
我在structs.h部分也收到了很多警告。我还尝试将structs.h定义更改为:
char RoomDesc1[][6] = {
但我仍然得到一个混乱的描述和许多警告。 我明确得到的警告是“警告:字符串数组的初始化字符串太长[默认情况下启用]”这很奇怪,因为我计算出最长的字符串并将其设置为该长度。取走数字并离开[]仍会产生相同的警告。
此时,我有点卡住了。我花了半个小时查看数组应该如何格式化,我找不到任何错误。有人可以帮忙吗?
答案 0 :(得分:1)
RoomDesc1
不是2D数组,它是const char *
的数组
const char * RoomDesc1[6] = {
"is a litter filled mess",
"is strewn with bones",
"is almost empty",
"feels like there is a presence",
"feels quite warm",
"feels chilly"
};
同样适用于RoomDesc2
答案 1 :(得分:1)
简短回答,将声明改为:
char RoomDesc1[6][30] = {
...
char RoomDesc2[3][14] = {
有关C和C ++中数组的详细说明,请参阅:http://www.cplusplus.com/doc/tutorial/arrays
答案 2 :(得分:0)
RoomDesc [0] = 0;只清除数组的第0个字节。 要清除整个数组,你应该使用memset函数
答案 3 :(得分:0)
避免重复调用strcat - 它不断搜索终止&#39; \ 0&#39;在连接之前,因此变得越来越慢(这是Shlemiel the Painter算法的一个例子)。而是使用snprintf:
int maxSize = 60;
snprintf( RoomDesc, maxSize, "%s on a %s", RoomDesc1[(rand() % 5], RoomDesc2[(rand() % 3)]);