0

I need to make such a check that the user enters only a value, if he enters a letter, or just some character without a number, then display an error message and enter a new value. For example, the input is "3.00", the output is "Invalid value! Please try again"

I want to understand how to do this, otherwise I did not find any information on the Internet

#include <iostream>
#include <cmath>

using namespace std;

long long byaka(long long a, long long b, long long& k, long long& w)
{
    if (b == 0)
    {
        k = 1;
        w = 0;
        return a;
    }
    long long d = byaka(b, a % b, k, w);
    k -= (a / b) * w;
    swap(k, w);
    return d;
}

int main() 
{
    long long a, b, c, k, w, d;
    cout << "A B C: \n";
    cin >> a >> b >> c;
    d = byaka(a, b, k, w);
    while (c % d != 0) 
    {
        cout << "Impossible! Vvedite A B C: \n";
        cin >> a >> b >> c; 
        d = byaka(a, b, k, w);
    }
    long long t = c / d * k, t2 = b / d;
    if (t == 0) cout << 0 << " " << c / d * w;
    if (t > 0) cout << t + t2 * (-(t / t2)) << " " << c / d * w - a / d * (-(t / t2));
    if (t < 0) cout << t + t2 * (-((t - t2 + 1) / t2)) << " " << c / d * w - a / d * ((-((t - t2 + 1) / t2)));
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • You can check the state of `cin` with `if (cin >> a >> b >> c) { ok to proceed...}` If it is not good see: [Why would we call cin.clear() and cin.ignore() after reading input?](https://stackoverflow.com/q/5131647) – 001 Nov 02 '22 at 20:55
  • Does this answer your question? https://stackoverflow.com/questions/50402749/cin-input-input-is-an-int-when-i-input-a-letter-instead-of-printing-back-inco/50403158#50403158 – Yunnosch Nov 02 '22 at 20:59
  • I need to make sure that the user enters only numbers, without letters, symbols, etc. that is, if you entered 1 2 3, then everything is OK, but if you enter a b c, then it came out - "Wrong. Enter a new value!" – Feldmanjoe Nov 02 '22 at 21:24

1 Answers1

0

Normally, if you need to verify what the user has entered, you have them enter the input as a string. Then you can check that it's all digits, and convert to a number if it is. If it's not, you'd usually give them an error message, and ask them for input again.

bool check_only_digits(std::string const &s) { 
    if (s.find_first_not_of("0123456789") != std::string::npos) {
        std::cerr << "Digits only please!";
        return false;
    }
    return true;
}

std::string s;

std::cout << "Please enter a number: ";

do {
    std::getline(std::cin, s);
} while (!check_only_digits(s));

long long i = std::stoll(s);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111