当我在下面的代码中使用 sscanf() 时,出于某种原因,它会将整行放在第一个字符串中,我没有发现任何问题。 Msg() 的输出类似于 PatchVersion=1.1.1.5 = °?¦§-
文件看起来像这样(除了每一行都是一个新行,不知道为什么它在 StackOverflow 上显示为一个)
PatchVersion=1.1.1.5
ProductName=tf
appID=440
代码:
bool ParseSteamFile()
{
FileHandle_t file;
file = filesystem->Open("steam.inf", "r", "MOD");
if(file)
{
int size = filesystem->Size(file);
char *line = new char[size + 1];
while(!filesystem->EndOfFile(file))
{
char *subLine = filesystem->ReadLine(line, size, file);
if(strstr(subLine, "PatchVersion"))
{
char *name = new char[32];
char *value = new char[32];
sscanf(subLine, "%s=%s", name, value);
Msg("%s = %s\n", name, value);
}
else if(strstr(subLine, "ProductName"))
{
char *name = new char[32];
char *value = new char[32];
sscanf(subLine, "%s=%s", name, value);
Msg("%s = %s\n", name, value);
}
}
return true;
}
else
{
Msg("Failed to find the Steam Information File (steam.inf)\n");
filesystem->Close(file);
return false;
}
filesystem->Close(file);
return false;
}
最佳答案
一个解决方案是使用(在我看来未被充分利用的)字符组格式说明符:
sscanf(subLine, "%[^=]=%s", name, value);
此外,在依赖它们之前,您应该使用 sscanf()
的返回值来验证您确实获得了这两个值。
关于c++ - sscanf() 无法正确识别格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4105992/