使用 sscanf 解析出两个字符串

发布于 2024-09-02 11:22:31 字数 401 浏览 0 评论 0原文

我有一个半 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白云不回头 2024-09-09 11:22:31

像往常一样,扫描集可能是你最好的答案:

sscanf(lineread, "%*[^\"]\"%[^\"]\"%*[^\"]\"%[^\"]\"", name, value);

当然,对于真正的代码,你还想限制转换的长度:

#include <stdio.h>

int main() { 
    char lineread[] = "<param name=\"Distance\" value=\"1000Km\" />";   
    char name[256], value[256];

    sscanf(lineread, "%*[^\"]\"%255[^\"]\"%*[^\"]\"%255[^\"]\"", name, value);

    printf("%s\t%s", name, value);
    return 0;
}

Edti:顺便说一句,sscanf 返回成功转换的数量,所以在你的原始代码中,你可能想要与 2 而不是 1 进行比较。

Edit2:这么多: %*[^\"]\" 表示“读取并忽略引号以外的字符”,然后读取并跳过引号。下一个 %255[^\"]\" 表示“读取除引号之外的最多 255 个字符,然后读取并跳过引号。然后重复整个模式以读取第二个字符细绳。

As usual, a scanset is probably your best answer:

sscanf(lineread, "%*[^\"]\"%[^\"]\"%*[^\"]\"%[^\"]\"", name, value);

Of course, for real code you also want to limit the lengths of the conversions:

#include <stdio.h>

int main() { 
    char lineread[] = "<param name=\"Distance\" value=\"1000Km\" />";   
    char name[256], value[256];

    sscanf(lineread, "%*[^\"]\"%255[^\"]\"%*[^\"]\"%255[^\"]\"", name, value);

    printf("%s\t%s", name, value);
    return 0;
}

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.

歌入人心 2024-09-09 11:22:31

原始代码的问题是 %s 仅在看到空格后停止。因此,name 得到的是 Distance",而不是预期的 Distance

The problem with the original code was that %s stops only after seeing a space. Hence, name gets Distance" not Distance as expected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文