我正试图通过C中的一个.txt文件进行解析
void parser()
{
FILE * rooms;
char * theString;
char * theToken;
char a[ROOM_STRING_LENGTH];
rooms = fopen("assets/rooms.txt", "r");
if(rooms == NULL)
{
printf("error opening file\n");
}
while(fgets(a, ROOM_STRING_LENGTH, rooms) != NULL)
{
theString = malloc((sizeof(char)*(strlen(a)+1)));
strcpy(theString, a);
theToken = strtok(theString, " ");
while (theToken != NULL)
{
printf("the next token: %s\n", theToken);
theToken = strtok(NULL, " ");
if(theToken[0] == 'd')
{
doorParser(theToken);
}
else if(theToken[0] == 'g' || theToken[0] == 'm' || theToken[0] == 'p' || theToken[0] == 'h')
{
iconParser(theToken);
}
}
if(theToken == NULL)
{
}
}
free(theString);
fclose(rooms);
}
void iconParser(char * theToken)
{
int k;
int item;
char posX;
char posY;
while(k <= (strlen(theToken)))
{
switch(theToken[k])
{
case 'g':
item = 1;
posY = theToken[1];
posX = theToken[3];
printf("the item: %d, the y position: %c, the x position: %c\n", item, posY, posX);
break;
case 'm':
item = 2;
posY = theToken[1];
posX = theToken[3];
break;
case 'p':
item = 3;
posY = theToken[1];
posX = theToken[3];
break;
case 'h':
item = 4;
posY = theToken[1];
posX = theToken[3];
break;
}
k++;
}
}
void doorParser(char * theToken)
{
int side;
char place;
switch(theToken[1])
{
case 'e':
{
side = 1;
place = theToken[2];
printf("the side: %d, the place: %c\n", side, place);
break;
}
case 'w':
{
side = 2;
place = theToken[2];
break;
}
case 's':
{
side = 3;
place = theToken[2];
break;
}
case 'n':
{
side = 4;
place = theToken[2];
break;
}
default:
{
}
}
}
这是我的.txt文件:
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,2
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,4
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,6
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,10
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,12
12X6 de8 dw3 ds5 g8,7 m3,4 p2,2 h2,14
我现在遇到的问题是,在它运行完一行或.txt文件之后,我得到了一个分段错误,而且我想知道如何将字符串(即char)的某个值转换成int值
最佳答案
首先,循环的结构没有任何意义:
while (theToken != NULL)
{
printf("the next token: %s\n", theToken);
theToken = strtok(NULL, " ");
if(theToken[0] == 'd') <<< This is dereferencing NULL after last token!
您正在使用
theToken
条件检查NULL
是否while
,然后获取下一个标记并立即使用它(通过尝试查找其第0个字符),即使它是NULL
。惯用的用法是
for (tok = strtok(str, " "); tok; tok = strtok(NULL, " "))
{
// Process the token here.
关于c - 在C中解析.text文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22392334/