I am trying to create a if else float on which when the user enters in a number value like 100.00 it should detect the users answer and if the user enters letters, then it should keep on repeating until the user puts a number in. But what is the fucntion or value that i have to use to do this, cause with my code now when I enter a word or letter it, bugs out and adds multiple lines in and tehn cuts the executible. whats the easy way of doing this.
float purchase;
std::cout << endl << "How much is the item you would like to
purchase: $"; //purchase enter text // we assume that the user enters
a valid score
std::cin >> purchase;
int main(){
if (!cin){ // figure out the purchase == no number value so loop works correctly
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max());
cout << "Please select a state from the following list:";
}
else {
cout << "The entered cost is invalid..." << endl;
cout << endl << "How much is the item you would like to purchase: $";
cin >> purchase; // float value from the users price that was entered
}
}
#include <iostream>
#include <string>
double getInput(const std::string&);
int main()
{
double input = getInput("Enter a double: ");
std::cout << "\nYou entered " << input << '\n';
}
double getInput(const std::string& query)
{
double input = 0.0;
std::string str_input = "";
// ask the question
std::cout << query;
while (true)
{
// retrieve the entire input and stuff it into a string
std::getline(std::cin, str_input);
try
{
// try to extract a double from the retrieved line of input
// an error is thrown if not a double
input = std::stod(str_input);
// the double was successfully retrieved, let's get out of here
break;
}
catch (...)
{
std::cout << "Input error....try again: ";
continue;
}
}
return input;
}
Enter a double: hello
Input error....try again: 15.5
You entered 15.5