Bumler

isNumber with overload

Oct 9th, 2020 (edited)
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. bool toNumberConv(std::string str, int &x)
  4. {
  5.     bool num = true;
  6.     unsigned int i = 0;
  7.     while(i < str.length() && num)
  8.     {
  9.         if (!isdigit(str[i]))
  10.         {
  11.             num = false;          
  12.         }
  13.         i++;
  14.     }
  15.     if(num)
  16.     {
  17.         x = stoi (str);
  18.     }
  19.     else
  20.     {
  21.         x = 0;
  22.     }
  23.     return num;
  24. }
  25.  
  26. bool toNumberConv(std::string str, double &x)
  27. {
  28.     int dots = 0;
  29.     bool num = true;
  30.     unsigned int i = 0;
  31.     while(i < str.length() && num)
  32.     {
  33.         if ((str[i] == '.') && dots == 0)
  34.         {
  35.             dots = 1;
  36.         }
  37.         else if (!isdigit(str[i]))
  38.         {
  39.             num = false;          
  40.         }
  41.         i++;
  42.     }
  43.     if(num && dots <= 1)
  44.     {
  45.         x = stod (str);
  46.     }
  47.     else
  48.     {
  49.         x = 0;
  50.     }
  51.     return num;
  52. }
  53.  
  54. int main()
  55. {
  56.     std::string str;
  57.     std::cin >> str;
  58.    
  59.     int toNumInt;
  60.     double toNumDouble;
  61.    
  62.     bool isNumInt = toNumberConv(str, toNumInt);
  63.     bool isNumDouble = toNumberConv(str, toNumDouble);
  64.    
  65.     if(isNumInt) std::cout << toNumInt << std::endl;
  66.     else std::cout << "Ez nem egy int szam\n";
  67.    
  68.     if(isNumDouble) std::cout << toNumDouble << std::endl;
  69.     else std::cout << "Ez nem egy double szam\n";
  70.    
  71.     return 0;
  72. }
  73.  
Add Comment
Please, Sign In to add comment