LazyCat
LazyCat

Reputation: 506

output string "nan" if value is 0

I need to output a number, unless it is 0, in which the output has to be "nan" I can't do

int x;
...
cout << (!x ? "nan" : x);

since the types in ternary expressions do not match. I can do

void f(ostream& o, int x)
{ 
    if (!x) o << x;
    else o << "nan";
}

which looks a bit ugly to me. Is there a better solution to this? Something, like

cout << nanify(x);

maybe?

Upvotes: 0

Views: 230

Answers (3)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

I'm not saying I would do it that way but you could install a custom std::num_get<char> facet to print nan when a 0 is printed:

#include <algorithm>
#include <iostream>
#include <locale>

class zero_num_put
    : public std::num_put<char> {
    iter_type do_put(iter_type out, std::ios_base& str, char_type fill, long v) const {
        if (v == 0) {
            static char nan[] = "nan";
            return std::copy(nan, nan + 3, out);
        }
        return std::num_put<char>::do_put(out, str, fill, v);
    }
};

int main()
{
    std::locale loc(std::locale(), new zero_num_put);
    std::cout.imbue(loc);
    std::cout << 0 << " " << 17 << "\n";
}

Upvotes: 3

Usiten
Usiten

Reputation: 15

You could use something along those lines:

std::string nanify(const int x) {
    if (x) { /* If not 0, return 'x' as a string */
        return std::to_string(x);
    }
    /* Else, return "nan" string */
    return "nan";
}

std::cout << nanify(0) << ' ' << nanify(15); /* nan 15 */ 

Upvotes: 0

user7351608
user7351608

Reputation: 451

Why not use this:

int x;
...
cout << (!x ? "nan" : std::to_string(x));

Upvotes: 2

Related Questions