Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 246
Sourav Kannantha B Avatar asked Oct 24 '25 16:10

Sourav Kannantha B


1 Answers

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.

like image 157
user17732522 Avatar answered Oct 27 '25 04:10

user17732522



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!