【问题标题】:How to skip whitespaces but not the newline如何跳过空格而不是换行符
【发布时间】:2013-12-18 02:08:05
【问题描述】:

我想从std::istream 中跳过所有SPs 和HTs,然后从中读取一个字符串直到第一个SPHT,然后跳过所有SPs 和@987654328 @s,然后阅读所有内容,直到换行符 \n

我试过了

stream >> str >> std::ws;
std::getline(stream, rest);

但不太有效,因为std::ws 吃换行符以及空格和水平制表。我想我能做到

stream >> str;
std::getline(stream, rest);
trim_leading_whitespace(rest);

甚至std::getline(stream, temp); do_regex_match("/* some complex regex */", temp, str, rest);

是否有可能仅使用iostream 相关的东西以某种方式修复第一次尝试?它个人看起来最简洁,当然欢迎任何关于如何简洁明了地编写它的建议。

【问题讨论】:

  • @AdriC.S. ignore 只忽略一个特定字符。当然,我可以设计类似while(stream.ignore(1, '\x20') || stream.ignore(1, '\t'));...实际上,让我检查一下。
  • 但是,如果你有std::numeric_limits<std::streamsize>::max()而不是count = 1,它不应该丢弃所有的空格吗?
  • 这不是工作流 >> str >> someChar; std::getline(流,休息); rest2 = someChar + rest;
  • @AdriC.S.不,ignore 会跳过所有内容,直到第一个 delim 字符。

标签: c++ iostream


【解决方案1】:

您可以创建自己的构面,将用户提供的空白字符注册到基础表中。创建用于启用/禁用此功能的操纵器是我将留给您的练习:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

class ctype : public std::ctype<char>
{
    template<class... Args>
    static mask* make_table(Args... args)
    {
       static std::vector<mask> table(classic_table(),
                                      classic_table() + table_size);
       typedef int pack[];

       (void)pack{ ((table[args] |= space), void(), 0) ... };
       table['\n'] &= ~space;

       return &v[0];
    }
public:
    template<class... Args>
    ctype(Args... args)
        : std::ctype<char>(make_table(args...)) { }
};

int main()
{
    std::istringstream iss("!@#abc");
    iss.imbue(std::locale(iss.getloc(), new ctype('!', '@', '#')));
    std::string str;

    std::getline(iss >> std::ws, str);
    std::cout << str; // "abc"
}

【讨论】:

    【解决方案2】:

    在读取行声明一个额外的流:

    std::string data; // <<-- trimmed data
    std::string line;
    std::getline(stream, line);
    std::istringstream line_buffer(line);
    line_buffer >> std::ws >> data;
    

    【讨论】:

      猜你喜欢
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 2014-06-02
      • 2010-10-17
      • 2015-11-08
      相关资源
      最近更新 更多