使用 sscanf 解析出两个字符串
我有一个半 xml 格式的文件,其中包含具有以下格式的行:
<param name="Distance" value="1000Km" />
字符串中的第一个字符通常是制表符或空格。 我一直在使用以下方法尝试解析两个字符串(从名称和值):
if(sscanf(lineread, "\t<param name=\"%s\" value=\"%s\" />", name, value) == 1)
{
//do something
}
名称和值是 char*
现在,结果始终相同:名称得到解析(我需要删除引号)和名称总是空的。 我做错了什么?
谢谢,代码值得赞赏。
杰西.
I have a semi xml formatted file that contains line with the following format:
<param name="Distance" value="1000Km" />
The first char in the string is usually a TAB or spaces.
I've been using the following to try to parse the two strings out (from name and value):
if(sscanf(lineread, "\t<param name=\"%s\" value=\"%s\" />", name, value) == 1)
{
//do something
}
name and value are char*
Now, the result is always the same: name gets parse (I need to remove the quotes) and name is always empty.
What am I doing wrong?
Thanks, code is appreciated.
Jess.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像往常一样,扫描集可能是你最好的答案:
当然,对于真正的代码,你还想限制转换的长度:
Edti:顺便说一句,sscanf 返回成功转换的数量,所以在你的原始代码中,你可能想要与 2 而不是 1 进行比较。
Edit2:这么多:
%*[^\"]\"
表示“读取并忽略引号以外的字符”,然后读取并跳过引号。下一个%255[^\"]\"
表示“读取除引号之外的最多 255 个字符,然后读取并跳过引号。然后重复整个模式以读取第二个字符细绳。As usual, a scanset is probably your best answer:
Of course, for real code you also want to limit the lengths of the conversions:
Edti: BTW, sscanf returns the number of successful conversions, so in your original code, you probably wanted to compare to 2 instead of 1.
Edit2: This much:
%*[^\"]\"
means "read and ignore characters other than a quote mark", then read and skip across a quote mark. The next%255[^\"]\"
means "read up to 255 characters other than a quote mark, then read and skip across a quote mark. That whole pattern is then repeated to read the second string.原始代码的问题是
%s
仅在看到空格后停止。因此,name
得到的是Distance"
,而不是预期的Distance
。The problem with the original code was that
%s
stops only after seeing a space. Hence,name
getsDistance"
notDistance
as expected.