我有以下一行,
*"1 $This is an open field west of a white house, with a boarded front door.$ 2 -1 -1 -1"*
此str中有六个值:房间号,描述,北,南,东,西
----' $'不应该在描述struct variabl
中输入我已成功使用sscanf作为前两个元素
sscanf(line, "%d",&room[count].room_number);
sscanf(line, "%*[^$]%*c%[^$]s", room[count].description);
但是我在检索北,南,东和西的价值时遇到了麻烦。
"%*[^$]%*[^$] %d"
是从str?
中检索北值(应该是2)的正确分隔符答案 0 :(得分:2)
通过以下方式编写复杂sscanf()
代码更为容易:
#define
和字符串文字串联来形成格式。" %n"
来测试是否成功。这允许更清晰的编码。 "%99[^$]"
是最多可扫描99个非美元符号字符的说明符。 "%*[^$]%*[^$] %d"
失败主要是因为它不会扫描任何$
。
s
结束时不需要"%99[^$]"
。 @aragaer
#include <stdio.h>
#include <stdlib.h>
#define F_PRE "*\""
#define F_RML " $"
#define F_RMR "$"
#define F_END "\"*"
int main(void) {
const char *line = "*\"1 $This is ... door.$ 2 -1 -1 -1\"*\n";
int Room_number, north, south, east, west;
char description[100];
int n = 0;
sscanf(line, F_PRE "%d" F_RML "%99[^$]" F_RMR "%d" "%d" "%d" "%d" F_END " %n",
&Room_number, description, &north, &south, &east, &west, &n);
if (n && (line[n] == '\0')) {
printf("%d <%s> %d %d %d %d\n", Room_number, description, north, south, east, west);
} else {
puts("Fail");
}
return 0;
}
输出
1 <This is ... door.> 2 -1 -1 -1