gpt4 book ai didi

c - fgets 不读 EOL?

转载 作者:太空宇宙 更新时间:2023-11-04 04:50:44 24 4
gpt4 key购买 nike

基本上我正在用 C 语言编写一个基于文本的角色扮演游戏,我想创建一个 map 系统。基本上,我遇到问题的功能是从如下所示的文件中读取“文本映射”:

----------\n
|c x [\n
| x |\n
] |\n
----------\0

它基本上是使用二维数组构建的。 *EDIT 我添加了 map 在实际数组中的样子。是不是因为我不喜欢终止每一行

这是我遇到问题的功能:

char** readMap(char* map_to_read,int h, int w){
FILE* fp;
int a = 0, b = 0;
char map_return[h][w];
char* c;

fp = fopen(map_to_read, "r");

for(a = 0; a < h; a++){
for(b = 0; b < w; b++){
c = (char*)malloc(sizeof(char) * w);
map_return[a][b] = fgets(c, w, fp);
printf("%s", c);
}
free(c);
}

fclose(fp);
return map_return;
}

直到最后一切都正常读取,因为 fgets() 没有读取 EOL。这是 printf 从内部看的样子:http://i.imgur.com/KojbjDm.png

我可以为此再找一双眼睛吗?

最佳答案

分析

What's the value in w? For your shown data, it should be at least 12 to get the newline too (10 characters, newline and null). You're going to have problems later because you can't (safely) return the local array map_return, but that's a separate bug. Also, you should be getting type mismatch warnings on the map_return[a][b] = fgets(c, w, fp); line because map_return[a][b] is a char and fgets() returns a char *. And you can't afford to free(c) if you're saving a pointer to it. There are so many problems here...

你回复了:

Basically it's array[h][w], so w represents the number of elements in one line of the array.

得到了进一步的回应:

So you need two separate chunks of memory. One is used to read the line and validate it. It can be simply char line[128];. You then use if (fgets(line, sizeof(line), fp) == 0) { ...process EOF/error...}. And assuming that passes, you validate the line and when it passes the validation, then you can arrange to copy up to w characters from the line into the map_return array. You have to decide whether you are playing with strings (terminated with a '\0') or not. You can make a case for either. You then have to deal with the problem of 'not returning a local variable'.

综合

我建议您更改函数的接口(interface),以便调用者为其分配内存。

此代码编译(但尚未运行)。它不会在读取的行上做太多验证;您可以决定还要做些什么。

#include <stdio.h>
#include <stdbool.h>

extern bool readMap(char* map_to_read, int h, int w, char map[h][w]);

bool readMap(char* map_to_read, int h, int w, char map[h][w])
{
FILE* fp;

if ((fp = fopen(map_to_read, "r")) == 0)
return false;

for (int a = 0; a < h; a++)
{
char line[128];
if (fgets(line, sizeof(line), fp) == 0)
{
fclose(fp);
return false;
}
for (int b = 0; b < w; b++)
{
// Validation
if (line[b] == '\n' || line[b] == '\0')
{
fclose(fp);
return false;
}
map[a][b] = line[b];
printf("%c", line[b]);
}
putchar('\n');
}

fclose(fp);
return true;
}

此代码假设您没有在 map 数组中存储以 null 结尾的字符串。

调用示例:

int h = 5;
int w = 10;
char map[h][w];

if (mapRead("somefile", h, w, map))
...process initialized map...
else
...report failure...

函数的错误报告很少;您可以根据需要对其进行改进。

关于c - fgets 不读 EOL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15737589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com