【问题标题】:Remove tabs with more than 5 in a line删除一行中超过 5 个的选项卡
【发布时间】:2015-08-05 20:17:56
【问题描述】:

我正在尝试从网站的源代码中提取 sn-p,现在我想删除每行中标记之前的所有空格和制表符。所以我将字符串复制到一个字符,现在我用 isspace 检查每个字符(也尝试过'\t'和'')每一行直到有一些其他字符,比如'

for(int i = 0;i < lines;i++){

    getline(codefile, buf);

    char *separator = new char[buf.size()+1];
    separator[buf.size()] = 0;
    memcpy(separator,buf.c_str(),buf.size());

    int chars = 0;

    for(int j = 0; j <= sizeof(separator); j++){

        if(isspace(separator[j])){
            chars++;    
        }
        else{
            break;
        }
    }

    char *newbuf= new char[buf.size()-chars+1];
    newbuf[buf.size()-chars] = 0;

    for(int k = 0; k <= buf.size()-chars+1; k++){
        newbuf[k] = separator[chars+k];
    }

    if(i > lcounter){
        cout << newbuf << i << endl;
    }

}

这是来自网站的源代码的 sn-p。您可以在 image 标记、结束的 figure 标记和 p 标记处看到它。他们有超过 5 个标签(抱歉,我不得不对其进行审查)。

<div class="xxx">

   <article class="xxx" data-id="0">
    <a href="link" class="tile" style="background-image:url('x.jpg');background-position:left center"  data-more="&lt;a href=x" data-clicks="&lt;i class=&quot;fa fa-eye&quot;&gt;&lt;/i&gt;" data-teaserimg="x.jpg">
    <time datetime="2015">
        <span>2015</span>
    </time>
    <h1 class="title">
        <span>x</span>
    </h1>
    <div class="x">x</div>
    <div class="x">x</div>      
    <div class="x">
        <figure class="x">
            <img src="x.jpg" width="1" height="1" alt="">
        </figure>
        <p>
            <strong>x</strong>xxx
        </p>
    </div>
</a>

抱歉,我无法发布图片,希望可以理解。

【问题讨论】:

  • 是时候学习如何使用调试器,以及如何在观察变量及其值的同时逐行执行代码。
  • 我觉得有几点值得怀疑,而这些都是关于您为什么使用动态内存分配的原因?不是一次,而是两次。为什么不简单地使用std::string,并且可能有关于如何修剪(即术语)前导空格的示例,例如this old answer here
  • 至于你的麻烦背后的原因,我猜你是在一个 32 位系统上,其中指针是 32 位(四个字节)。你真的需要了解更多关于sizeof operator的信息。

标签: c++ file whitespace getline


【解决方案1】:

sizeof(separator) 应该是strlen(separator)

sizeof 是separator 变量的大小,而不是字符串的长度。因为separatorchar*,所以这是四个字节。现在你明白为什么当你有超过五个标签时你的代码不起作用了吗?

正如其他人指出的那样,确实没有理由将字符串复制到分隔符数组。为什么不只检查角色所在的位置? isspace(buf[j])isspace(separator[j]) 一样好用。

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2021-10-07
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多