Advertisement
Mike_be

Input check

Oct 15th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. string input = "";
  2.  
  3. long double read(string startMes, string stringError, string dotError) { //Checks variable for correct input (number)
  4.     cout << startMes << ": ";
  5.     getline(cin, input);
  6.     dotCount = 0;
  7.     bool onlyDigits = true;
  8.     string dummy;
  9.     while (!onlyDigits || (dotCount >= 0 && dotCount < 2)) {
  10.         for (int i = input.length() - 1; i >= 0; i--) {
  11.             if (!isdigit(input[i])) {
  12.                 if (input[i] == '.') dotCount += 1;
  13.                 else onlyDigits = false;
  14.  
  15.             }
  16.         }
  17.         if (onlyDigits && dotCount < 2) {
  18.             return stod(input.c_str());
  19.         }
  20.         else {
  21.             if (!onlyDigits) { cout << stringError << ", type again: "; }
  22.             else if (dotCount > 1) { cout << dotError << ", type again: "; }
  23.             getline(cin, input);
  24.             onlyDigits = true;
  25.             dotCount = 0;
  26.         }
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement