Search code examples
c++doubleconsole-applicationuser-inputcin

How to give 'infinity' as a value to double through cin in C++?


In my program, I'm taking a slope value as input from the user. The code snippet looks like this:

double m;
std::cout << "Enter slope value:";
std::cin >> m;

But currently I'm unable to give 'infinity' as slope value to this. If type 'inf', m will store 0 maybe due to parse error. If I type really large number like 1e1000, m will store DBL_MAX i.e. 1.79769e+308.

So what should I type in console, so that m contains value of 'infinity'? (slope of vertical line).


Solution

  • So what should I type in console, so that m contains value of 'infinity'? (slope of vertical line).

    I don't think std::istream::operator>>(double&) currently supports that.

    Ultimately it will use std::strtod to convert the extracted string to a double and std::strtod should accept INF and INFINITY, ignoring case and with optional +/- prefix.

    However, currently the extraction of characters happens through std::num_get::do_get which considers only the characters 0123456789abcdefpxABCDEFPX+- as valid.

    In LWG 2381, which resolves some inconsistencies between >> and strtod, inifinities and NaNs are also mentioned as not in scope of the resolution.

    So you'll need to read in a string and call std::strtod/std::stod/std::from_chars on it manually.