Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <charconv>
- #include <iomanip>
- #include <iostream>
- #include <limits>
- #include <string>
- using namespace std;
- long double GetLongDouble() {
- string str;
- long double result;
- bool is_converted = false;
- do
- {
- getline(cin, str);
- auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
- if (ec == std::errc())
- {
- return result;
- }
- else if (ec == std::errc::invalid_argument)
- {
- std::cout << "This is not a number.\n";
- }
- else if (ec == std::errc::result_out_of_range)
- {
- std::cout << "This number is larger than an long double.\n";
- }
- std::cin.clear(); // reset the fail flags
- std::cin.ignore(std::numeric_limits< std::streamsize >::max(), '\n'); // ignore the bad input until line end
- cout << "Please enter value again\n";
- } while (true);
- /*
- do
- {
- try
- {
- getline(cin, long_double);
- //https://en.cppreference.com/w/cpp/string/basic_string/stof
- result = stold(long_double);
- std::cin.clear(); // reset the fail flags
- std::cin.ignore(std::numeric_limits< std::streamsize >::max(), '\n'); // ignore the bad input until line
- // end
- return result;
- } catch (invalid_argument const &ex)
- {
- cout << "Invalid argument.\n";
- } catch (out_of_range const &ex)
- {
- cout << "Argument value is out of range\n";
- }
- cout << "Please enter value again\n";
- std::cin.clear(); // reset the fail flags
- std::cin.ignore(std::numeric_limits< std::streamsize >::max(), '\n'); // ignore the bad input until line end
- } while (true);
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement