【问题标题】:Using stringstream instead of `sscanf` to parse a fixed-format string使用 stringstream 而不是 `sscanf` 来解析固定格式的字符串
【发布时间】:2011-05-31 17:20:16
【问题描述】:

我想使用stringstream 提供的工具从固定格式的string 中提取值,作为sscanf 的类型安全替代方案。我该怎么做?

考虑以下特定用例。我有以下固定格式的std::string:

YYYYMMDDHHMMSSmmm

地点:

YYYY = 4 digits representing the year
MM = 2 digits representing the month ('0' padded to 2 characters)
DD = 2 digits representing the day ('0' padded to 2 characters)
HH = 2 digits representing the hour ('0' padded to 2 characters)
MM = 2 digits representing the minute ('0' padded to 2 characters)
SS = 2 digits representing the second ('0' padded to 2 characters)
mmm = 3 digits representing the milliseconds ('0' padded to 3 characters)

以前我是按照这些思路做的:

string s = "20101220110651184";
unsigned year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0;    
sscanf(s.c_str(), "%4u%2u%2u%2u%2u%2u%3u", &year, &month, &day, &hour, &minute, &second, &milli );

宽度值是幻数,没关系。为了类型安全,我想使用流来提取这些值并将它们转换为unsigneds。但是当我尝试这个时:

stringstream ss;
ss << "20101220110651184";
ss >> setw(4) >> year;

year 保留值0。应该是2010。

我该如何做我想做的事?我不能使用 Boost 或任何其他 3rd 方库,也不能使用 C++0x。

【问题讨论】:

  • *Bill 等不及要他的“Standard C++ IOstreams and Locales”副本了...+1
  • setw() 用于写入输出。它不适用于阅读。
  • 也许你应该在提取第一个字段之前回到流的开头。
  • @Ben:或者更好,只是std::stringstream ss("20101220110651184");
  • @Karl:无关紧要,但只要说它不是我们树的一部分就够了。

标签: c++


【解决方案1】:

一个不是特别有效的选择是构造一些临时字符串并使用词法转换:

std::string s("20101220110651184");
int year = lexical_cast<int>(s.substr(0, 4));
// etc.

lexical_cast 只需几行代码即可实现; Herb Sutter 在他的文章"The String Formatters of Manor Farm."

中提出了最低要求

这不是您正在寻找的,但它是一种从字符串中提取固定宽度字段的类型安全方法。

【讨论】:

  • 我不能使用lexical_cast,因为那是 Boost 的一部分。
  • 虽然我可以再次使用流或一些atoi 类型的东西。不过,我希望我能以更自然的方式完成此任务。
  • @John:你可以很容易地自己编写。我已经链接到 Herb Sutter 的一篇文章,其中介绍了一个非常基本的实现(七行格式良好的代码)。或者,我在my first Stack Overflow post发布了一个非常简单的版本;那是两行代码。
【解决方案2】:

呃,如果是固定格式,你为什么不这样做呢?

  std::string sd("20101220110651184");
  // insert spaces from the back
  sd.insert(14, 1, ' ');
  sd.insert(12, 1, ' ');
  sd.insert(10, 1, ' ');
  sd.insert(8, 1, ' ');
  sd.insert(6, 1, ' ');
  sd.insert(4, 1, ' ');
  int year, month, day, hour, min, sec, ms;
  std::istringstream str(sd);
  str >> year >> month >> day >> hour >> min >> sec >> ms;

【讨论】:

  • 您基本上是在创建一个新的以空格分隔的字符串,>> 运算符可以解析它,因为它包含空格......效率不高。
【解决方案3】:

我使用以下,它可能对你有用:

template<typename T> T stringTo( const std::string& s )
   {
      std::istringstream iss(s);
      T x;
      iss >> x;
      return x;
   };

template<typename T> inline std::string toString( const T& x )
   {
      std::ostringstream o;
      o << x;
      return o.str();
   }

这些模板需要:

#include <sstream>

用法

long date;
date = stringTo<long>( std::cin );

YMMV

【讨论】:

  • 在stringTo函数中,检查iss提取后的状态以确保提取成功并正确处理错误非常重要(抛出异常,返回错误代码,中止应用程序,随便)。
  • +1 这基本上是@James 上面所建议的。我希望使用 StdLib 已经提供的东西,但我可能不得不自己编写
【解决方案4】:

来自here,您可能会发现这很有用:

template<typename T, typename charT, typename traits>
std::basic_istream<charT, traits>&
  fixedread(std::basic_istream<charT, traits>& in, T& x)
{
  if (in.width(  ) == 0)
    // Not fixed size, so read normally.
    in >> x;
  else {
    std::string field;
    in >> field;
    std::basic_istringstream<charT, traits> stream(field);
    if (! (stream >> x))
      in.setstate(std::ios_base::failbit);
  }
  return in;
}

setw() 仅适用于读取字符串 cstrings。上面的函数使用了这个事实,读入一个字符串,然后将其转换为所需的类型。您可以将它与setw() 或ss.width(w) 结合使用,以读取任何类型的固定宽度字段。

【讨论】:

  • +1 这也是@James 所建议的。我在这里感觉到了一种趋势...... :)
【解决方案5】:
template<typename T>
struct FixedRead {
    T& content;
    int size;
    FixedRead(T& content, int size) :
            content(content), size(size) {
        assert(size != 0);
    }
    template<typename charT, typename traits>
    friend std::basic_istream<charT, traits>&
    operator >>(std::basic_istream<charT, traits>& in, FixedRead<T> x) {
        int orig_w = in.width();
        std::basic_string<charT, traits> o;
        in >> setw(x.size) >> o;
        std::basic_stringstream<charT, traits> os(o);
        if (!(os >> x.content))
            in.setstate(std::ios_base::failbit);
        in.width(orig_w);
        return in;
    }
};

template<typename T>
FixedRead<T> fixed_read(T& content, int size) {
    return FixedRead<T>(content, size);
}

void test4() {
    stringstream ss("20101220110651184");
    int year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0, ms = 0;
    ss >> fixed_read(year, 4) >> fixed_read(month, 2) >> fixed_read(day, 2)
            >> fixed_read(hour, 2) >> fixed_read(min, 2) >> fixed_read(sec, 2)
            >> fixed_read(ms, 4);
    cout << "year:" << year << "," << "month:" << month << "," << "day:" << day
            << "," << "hour:" << hour << "," << "min:" << min << "," << "sec:"
            << sec << "," << "ms:" << ms << endl;
}

【讨论】:

    【解决方案6】:

    ps5mh 的解决方案非常好,但不适用于包含空格的字符串的固定大小解析。以下解决方案解决了这个问题:

    template<typename T, typename T2>
    struct FixedRead
    {
        T& content;
        T2& number;
        int size;
        FixedRead(T& content, int size, T2 & number) :
            content(content), number(number), size(size)
        {
            assert (size != 0);
        }
        template<typename charT, typename traits>
        friend std::basic_istream<charT, traits>&
        operator >>(std::basic_istream<charT, traits>& in, FixedRead<T,T2> x)
        {
            if (!in.eof() && in.good())
            {
                std::vector<char> buffer(x.size+1);
                in.read(buffer.data(), x.size);
                int num_read = in.gcount();
                buffer[num_read] = 0; // set null-termination of string
                std::basic_stringstream<charT, traits> os(buffer.data());
                if (!(os >> x.content))
                    in.setstate(std::ios_base::failbit);
                else
                    ++x.number;
            }
            return in;
        }
    };
    template<typename T, typename T2>
    FixedRead<T,T2> fixedread(T& content, int size, T2 & number) {
        return FixedRead<T,T2>(content, size, number);
    }
    

    这可以用作:

    std::string s  = "90007127       19000715790007397";
    std::vector<int> ints(5);
    int num_read = 0;
    std::istringstream in(s);
    in >> fixedread(ints[0], 8, num_read) 
       >> fixedread(ints[1], 8, num_read) 
       >> fixedread(ints[2], 8, num_read) 
       >> fixedread(ints[3], 8, num_read) 
       >> fixedread(ints[4], 8, num_read);
    // output: 
    //   num_read = 4 (like return value of sscanf)
    //   ints = 90007127, 1, 90007157, 90007397
    //   ints[4] is uninitialized
    

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多