scanf 全部跳过直到一个字符串 [英] scanf skip all until a string

查看:32
本文介绍了scanf 全部跳过直到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 scanf 跳过所有字符,直到到达特定字符串.

Is it possible using scanf to skip all characters until I reach s specific string.

我有一个 html 文件,我想跳过包含此字符串之前的所有字符:"<h2><a href=",然后读取两个引号之间的 http 链接.>

I have an html file and I want to skip all characters before and including this string: "<h2><a href=" and then read http link between two quotes.

推荐答案

我偶然发现了一个多么古老的问题.尽管如此,它仍然在这里,我想我已经有了一个很好的答案.那么,为什么不留给后代,对吧?

What an old question I've stumbled upon. Nevertheless, it's still here and I think I've got a good answer. So, why not leave for the following generations, right?

您被告知 scanf 不能这样做.好吧,我不同意,原因如下:

You've been told scanf can't do it. Well, I disagree, and here is why:

scanf 可以忽略所有内容,直到找到要查找的字符串的第一个字母

scanf can ignore everything until it finds the first letter of the sought string

scanf ("%*[^<]");

然后它可以尝试忽略您要查找的字符串(逐个字符).

Then it can try to ignore the string you are looking for (char by char).

found = scanf ("<h2><a href=\"%[^\"]", str_link) == 1;

如果它还不是它,它将失败并停止执行,永远不会到达 %[^\"] 命令,该命令读取/存储所有内容直到 " 找到字符.

It will fail in case it is not it yet and will stop executing, never getting to the %[^\"] command, which reads/stores everything until " character is found.

在这种情况下,它返回 0EOF,因为无法执行扫描(它返回它能够填充多少变量)

In such a case, it returns 0, or EOF, for not being able to execute the scan (it returns how many of the variable it was able to fill)

现在,如果确实找到了,它将最终执行读取并返回1.

Now, if it does find, it will finally execute the reading and returns 1.

  • 注意:您应该查看文档以获取准确信息,这些信息可以在 cplusplus.com 上找到

  • note: you should check the documentation for precise information, which can be found at cplusplus.com

while ( !found && !feof(stdin) )
{
    scanf ("%*[^<]");
    found = scanf ("<h2><a href=\"%[^\"]", str_link) == 1;
}

我想文件的其余部分可以被忽略.由你决定.

I suppose the rest of the file could just be ignored. Up to you.

我想这是一个很好的方法,因为它充分利用了 scanf 的速度,并且不需要您存储整个文件.这个想法可以应用于许多其他任务.

This is a good method, I suppose, because it takes full advantage of scanf's speed, and it doesn't require you to store the whole file. The idea can be applied to many other tasks.

scanf 是一个非常强大的工具,虽然有点棘手.

scanf is a very powerful tool, though a bit tricky.

这篇关于scanf 全部跳过直到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆