2017-06-12 44 views
0

所以通常单独的号码,如果我想在一些数字,foo插入区域适当分离,我会做这样的事情:逗号没有字符串流

ostringstream out; 

out.imbue(locale("en-US")); 
out << foo; 

然后,我可以只使用out.str()作为分隔的字符串: http://coliru.stacked-crooked.com/a/054e927de25b5ad0

不幸的是我一直被要求在我目前的项目中不要使用stringstreams。有没有其他办法可以实现这个目标?理想的语言环境依赖的方式?

+0

所以,你想一个数字转换为千个分隔字符串或字符串千分隔字符串或者你只是需要输出这种方式? – NathanOliver

+0

@NathanOliver是的,显然我可以手动插入它们。但是这不会是适合当地语言的:( –

+0

)难道你不能仅仅使用[this](https://stackoverflow.com/questions/17530408/print-integer-with-thousands-and-millions-separator)吗?除非你真的需要一个字符串 – NathanOliver

回答

1

所以这个答案是杰里棺材的答案的C++蒸馏到这样一个问题:Cross Platform Support for sprintf's Format '-Flag

template <typename T> 
enable_if_t<is_integral_v<remove_reference_t<T>>, string> poscommafmt(T N, const numpunct<char>& fmt_info) { 
    string result = to_string(N % 10); 
    const auto group = fmt_info.grouping(); 
    auto places = 0U; 

    for (auto posn = '\1'; 0 != (N /= 10); ++posn, result = to_string(N % 10) + result) { 
     if (group[places] == posn) { 
      if (places + 1U < size(group)) { 
       ++places; 
      } 
      posn = '\0'; 
      result = fmt_info.thousands_sep() + result; 
     } 
    } 
    return result; 
} 

template <typename T> 
enable_if_t<is_integral_v<remove_reference_t<T>>, string> commafmt(const T N, const numpunct<char>& fmt_info) { 
    return N < 0 ? '-' + poscommafmt(-N, fmt_info) : poscommafmt(N, fmt_info); 
} 

当然,这从相同的2的补否定问题受到影响。

这肯定会受益于C++的string内存管理,还有能力传入一个特定的numpunct<char>,它不一定是当前的语言环境。例如是否cout.getloc() == locale("en-US")您可以拨打:commafmt(foo, use_facet<numpunct<char>>(locale("en-US")))

Live Example

0

设置管道。使用链接到代码construct an ofstream and ifstream from a file descriptor,然后输出到一个和从另一个读取。

这是一个奇怪和扭曲的解决方案。但是,那么你必须使用语言环境的想法,必须存储的东西,并不能使用stringstream也是奇怪的。所以,他们给你奇怪的要求,他们得到了奇怪的代码。

+1

哈哈,我可以保证这不会让它过去审查:) –

+1

@JonathanMee - 那么你可以问他们一个更好的方式来满足要求。:-)有时候,这是迫使愚蠢的决定得到他们应得的审查的最佳方式。我告诉测试部门哪些测试用例可以触发我知道的错误,但开发人员不会承认。有时它是组织而不是你必须破解的代码。 – Omnifarious

+0

这可能是一个合理的建议。当编写一个单独的程序来解决问题时,作为一个解决方案被抛出,你知道事情变得非常糟糕。 –

相关问题