不能从不区分大小写的字符串中提取double?

时间:2011-10-09 13:29:00

标签: c++ string case-insensitive stdstring istringstream

我试图想出一个不区分大小写的字符串,我在网上找到了以下内容

http://www.gotw.ca/gotw/029.htm

所以基本上我的代码提出了一个不区分大小写的字符串如下

struct ci_char_traits : public std::char_traits<char> {

    static bool eq( char c1, char c2 )
    { return toupper(c1) == toupper(c2); }

    static bool ne( char c1, char c2 )
    { return toupper(c1) != toupper(c2); }

    static bool lt( char c1, char c2 )
    { return toupper(c1) <  toupper(c2); }

    static int compare(const char* s1, const char* s2, size_t n )
    { return memicmp( s1, s2, n ); }

private:
    static int memicmp(const void *s1, const void *s2, size_t n) {

        if (n != 0) {
            const unsigned char *p1 = (const unsigned char *)s1, *p2 = (const unsigned char *)s2;
            do {
                if (toupper(*p1) != toupper(*p2))
                    return (*p1 - *p2);
                p1++;
                p2++;
            } while (--n != 0);
        }
        return 0;
    }
};

// case insensitive string type definition
typedef std::basic_string<char, ci_char_traits> ci_string;

// provide standard output for case insensitive string
template<typename char_type, typename traits_type, typename allocator_type>
inline std::basic_ostream<char_type, traits_type>&
operator<<(std::basic_ostream<char_type, traits_type>& os,
           const std::basic_string<char_type, ci_char_traits, allocator_type>& str) {
    return std::__ostream_insert(os, str.data(), str.size());
}

所以类型定义是字符串。现在我遇到的问题是,我无法使用这个自定义字符串的函数,因为它使用常规字符串。以下模板函数从字符串中获取值,但

template <typename T, class string_type, typename counter_type>
T stream_cast(const string_type& s) {

  typedef typename string_type::value_type char_type;
  typedef typename string_type::traits_type traits_type;

  typename std::basic_istringstream<char_type, traits_type> iss(s);

  T x;
  char c;
  if (!(iss >> x) || iss.get(c))
     cout<<"*** ERROR *** Bad Conversion!"<<endl;
  return x;
} 

我调用此函数从字符串中获取double,如下所示:

ci_string str("2.0");
double test = stream_cast<double>(str);

但是我对不区分大小写的字符串的定义有问题,因为通过运算符评估了流对象!始终失败(对于此字符串类型,行!(iss&gt;&gt; x)始终为true。)

有人知道我为什么遇到这个问题吗?提前感谢您花时间阅读这篇长篇文章。

AA

1 个答案:

答案 0 :(得分:1)

您编写了自定义输出运算符“operator&gt;&gt;”,但没有输入运算符“operator&lt;&lt;”,这就是您需要的那个。

这很有效:

ci_string str("2.0");
std::cout << str << std::endl;

因为运营商&gt;&gt;。

但是

std::cin >> str

没有。