1

I am creating a program that I want the user to be able to add more 'money' to their account. They would be entering how much money they want to add to it.

So after the user has entered how much money they want to add to their account, I want to check if a valid input has been entered (a number and not a character) and if a number has been added, the program continues like normal, but if not then it will output a message to the user.

I have tried something like this to get the users input and try to check it. (userMoney and userMoneyAdd are both float)

cout << "Enter the amount of money you want to enter in £'s" << endl;
cin >> userMoneyAdd;
cout << "You entered " << userMoneyAdd << endl;

if (userMoneyAdd == (int)userMoneyAdd) {
    cout << "you entered a number" << endl;
}
else {
    cout << "You have not entered a number" << endl;
}
James Risner
  • 5,451
  • 11
  • 25
  • 47
squiddy
  • 11
  • 1
  • 6
    The operator `>>` will stop reading at once when it detects a non-digit character, leaving it in the input buffer. If the input doesn't start with a digit, then it will set the `failbit` flag on the stream. If you want to do input with validation I suggest reading a whole line (as a string, with e.g. `std::getline`) and the converting it to an `int` value (with e.g. `std::stoi`). – Some programmer dude Dec 16 '22 at 03:59
  • 1
    Since `userMoneyAdd` is a `float`, it stores a number—regardless of user input. You can’t look into it and expect to see some other type of value. – Davis Herring Dec 16 '22 at 04:21
  • 1
    Storing monetary amounts in a `float` is probably a bad idea. – n. m. could be an AI Dec 16 '22 at 04:37

2 Answers2

0

You can use Regex which checks a string to have specific characters. appropriate Regex expression can be: "[0-9]+"- only numeric characters. if you want float number you can use this expression: "([0-9]+)(\.?([0-9]+))"

string money;
regex str_expr ("[0-9]+");//"([0-9]+)(\.?([0-9]+))" for float
cin>>money;
if(regex_match (str,str_expr))
    //convert the string to int
else
    cout << "You have not entered a number" << endl;
starball
  • 20,030
  • 7
  • 43
  • 238
Rachel
  • 51
  • 5
0

You can use std::stoi(...) to convert string to integer and using try catch if it was not number.

(if you have float numbers , So you can see std::string to float or double , stof method std::stof)

#include <iostream>
#include <string>

int main() {
  try {
    auto a1 = std::stoi("h024");
    //    auto a1 = std::stoi("24"); // ok
    std::cout << a1 << std::endl;
  } catch (std::exception const& err) {
    std::cout
        << "You did not enter valid input(number) , error in parsing input."
        << std::endl;
  }
  return 0;
}