Advertisement
Derga

Untitled

Sep 16th, 2023 (edited)
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <charconv>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <limits>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. long double GetLongDouble() {
  10.     string str;
  11.     long double result;
  12.     bool is_converted = false;
  13.  
  14.     do
  15.     {
  16.         getline(cin, str);
  17.         auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
  18.  
  19.         if (ec == std::errc())
  20.         {
  21.             return result;
  22.         }
  23.         else if (ec == std::errc::invalid_argument)
  24.         {
  25.             std::cout << "This is not a number.\n";
  26.         }
  27.         else if (ec == std::errc::result_out_of_range)
  28.         {
  29.             std::cout << "This number is larger than an long double.\n";
  30.         }
  31.  
  32.         std::cin.clear();                                                        // reset the fail flags
  33.         std::cin.ignore(std::numeric_limits< std::streamsize >::max(), '\n');    // ignore the bad input until line end
  34.         cout << "Please enter value again\n";
  35.     } while (true);
  36.  
  37.     /*
  38.     do
  39.     {
  40.         try
  41.         {
  42.             getline(cin, long_double);
  43.            
  44.             //https://en.cppreference.com/w/cpp/string/basic_string/stof
  45.             result = stold(long_double);
  46.             std::cin.clear();                                                        // reset the fail flags
  47.             std::cin.ignore(std::numeric_limits< std::streamsize >::max(), '\n');    // ignore the bad input until line
  48.                                                                                      // end
  49.             return result;
  50.            
  51.         } catch (invalid_argument const &ex)
  52.         {
  53.             cout << "Invalid argument.\n";
  54.         } catch (out_of_range const &ex)
  55.         {
  56.             cout << "Argument value is out of range\n";
  57.         }
  58.         cout << "Please enter value again\n";
  59.         std::cin.clear();                                                          // reset the fail flags
  60.         std::cin.ignore(std::numeric_limits< std::streamsize >::max(), '\n');      // ignore the bad input until line end
  61.     } while (true);
  62.     */
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement