关于读取键值对的 c:fscanf 问题

fscanf issue with reading in key-value pairs

编辑:自从被问到,我使用的是 Visual Studio 2013 Ultimate,它没有发出任何警告。

我对 C 有点陌生,文件 i/o 对我来说一直是个问题。我将如何以"keyName:valueName"的形式解析键值对?我的问题开始发挥作用,因为我的值可能是字符串、浮点数或无符号整数。

我正在使用 SDL2 编写游戏,并且尝试将各个演员的尽可能多的配置保存在单独的 .actor 文件中。按照一些示例代码,我设法通过 fscanf 读取了该对的关键部分,但是当我尝试将值 fscanf 到我的演员时,我得到了一个异常。

播放器.actor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
folder: images/Player/
scale: 1.0,1.0
color: 255,255,255,255
colorSpecial: 10,255,100,255
xOffset: 1
numAnimations: 3

name: idle
filename: playerIdle.png
length: 8
frameWidth: 39
frameHeight: 87
frameRate: 0.75
type: loop

name: attack
filename: playerPunch.png
length: 8
frameWidth: 50
frameHeight: 82
frameRate: 0.75
type: once

name: walk
filename: playerWalk.png
length: 7
frameWidth: 50
frameHeight: 82
frameRate: 0.85
type: loop

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void LoadActor(Actor *actor, char *filename)
{
  FILE * file;
  char buf[512];
  char* imageFile ="";
  int i = 0;

  file = fopen(filename,"r");

  if (!file)
  {
    return NULL;
  }

  rewind(file);

  while (fscanf(file,"%s", buf) != EOF) //this works
  {
    if (strcmp(buf,"numAnimations:") == 0) // this works
    {
        fscanf(file,"%i", i); // this doesn't?

        continue;
    }
  }
}

相关讨论

  • fscanf(file,"%i", &i); 你需要传递地址。
  • 你应该得到一个警告。你的编译器是什么?
  • rewind(file); 没用,你只需打开文件
  • 为什么 continue 在 while ?你不需要它来循环^^
  • Visual Studio 2013 Ultimate,我没有注意到我仍然在那里继续。
  • 编译器对 fscanf(file,"%i", i) 什么也没说?
  • 作为旁注,您最好使用现成的配置文件解析器库,而不是重新发明轮子。
  • @bruno,一点也不
  • @IanAbbott 我将不得不对此进行调查,因为我已经在这里待了一天多
  • 极好的。查看请求更多警告的选项,很多编译器都有这种选项(例如 gcc 有例如 -pedantic -Wextra)
  • 您需要提高编译器的默认警告级别。
  • 我的 MSVC 还警告:警告 C4098: 'LoadActor': 'void' 函数返回值。为什么函数 LoadActor 不使用它的参数 Actor *actor?
  • 对于 VS,它应该在 project properties a?’ C/C++ a?’ General a?’ Warning Level 下。将其设置为"EnableAllWarnings (/Wall)"。但我只是试了一下,仍然没有得到警告。
  • @WeatherVane 我想我解决了这个问题,是因为返回 NULL?
  • 没错,void 函数返回了 NULL。
  • 我现在已经启用了所有警告,所以我会回到那个。

when I attempt to fscanf the value in to my actor I get an exception.

1
       fscanf(file,"%i", i); // this doesn't?

fscanf(file,"%i", &i); 你需要传递地址。
——约翰尼·莫普


以上是关于读取键值对的 c:fscanf 问题的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>