您可以使用一個流處理器或修改底層區域:
機械手:
#include <cmath>
#include <ostream>
template <typename T>
struct FloatFormat
{
const T value;
FloatFormat(const T& value)
: value(value)
{}
void write(std::ostream& stream) const {
if(std::isnan(value))
stream << "Not a Number";
else
stream << value;
}
};
template <typename T>
inline FloatFormat<T> float_format(const T& value) {
return FloatFormat<T>(value);
}
template <typename T>
inline std::ostream& operator << (std::ostream& stream, const FloatFormat<T>& value) {
value.write(stream);
return stream;
}
int main() {
std::cout << float_format(std::numeric_limits<double>::quiet_NaN()) << '\n';
}
區域設置:
#include <cmath>
#include <locale>
#include <ostream>
template<typename Iterator = std::ostreambuf_iterator<char>>
class NumPut : public std::num_put<char, Iterator>
{
private:
using base_type = std::num_put<char, Iterator>;
public:
using char_type = typename base_type::char_type;
using iter_type = typename base_type::iter_type;
NumPut(std::size_t refs = 0)
: base_type(refs)
{}
protected:
virtual iter_type do_put(iter_type out, std::ios_base& str, char_type fill, double v) const override {
if(std::isnan(v))
out = std::copy(std::begin(NotANumber), std::end(NotANumber), out);
else
out = base_type::do_put(out, str, fill, v);
return out;
}
virtual iter_type do_put(iter_type out, std::ios_base& str, char_type fill, long double v) const override {
if(std::isnan(v))
out = std::copy(std::begin(NotANumber), std::end(NotANumber), out);
else
out = base_type::do_put(out, str, fill, v);
return out;
}
private:
static const char NotANumber[];
};
template<typename Iterator>
const char NumPut<Iterator>::NotANumber[] = "Not a Number";
#include <iostream>
#include <limits>
int main() {
#if 1
{
const std::size_t NoDestroy = 1;
NumPut<> num_put(NoDestroy);
std::locale locale(std::cout.getloc(), &num_put);
std::locale restore_locale = std::cin.getloc();
std::cout.imbue(locale);
std::cout << std::numeric_limits<double>::quiet_NaN() << '\n';
// The num_put facet is going out of scope:
std::cout.imbue(restore_locale);
}
#else
{
// Alternitvely use a reference counted facet and pass the ownership to the locales:
auto num_put = new NumPut<>();
std::locale locale(std::cout.getloc(), num_put);
std::cout.imbue(locale);
std::cout << std::numeric_limits<double>::quiet_NaN() << '\n';
}
#endif
std::cout << std::numeric_limits<double>::quiet_NaN() << '\n';
}
*我既需要產生相同的輸出*。聽起來像XY問題... –
數字輸出最終調用['std :: num_put :: do_put'](http://en.cppreference.com/w/cpp/locale/num_put/put)使用['std :: printf'](http://en.cppreference.com/w/cpp/io/c/fprintf)格式化輸出。和['std :: printf'](http://en.cppreference.com/w/cpp/io/c/fprintf)參考頁面一樣,NaN的輸出應該是'nan'或'nan(char_sequence )'。 (哪一個是實現定義的)這意味着Visual Studio是錯誤的。這也意味着,即使對於兼容的編譯器和庫,你有兩個替代輸出來處理 –
所以問題可能是如何強制VS2010輸出「nan」而不是「1.#QNAN」....不是VS2015遵循標準和輸出「南」,這是好的。 – jpo38