how do I validate user input as a double in C++?
Try this:
while (1) {
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
This basically clears the error state, then reads and discards everything that was entered on the previous line.
How to make sure input is a double in the C programming language
You probably want a code fragment more like this:
double number;
do {
printf("Enter a double: ");
scanf("%*c"); // burn stdin so as not to buffer up responses
} while (1 != scanf("%lf", &number));
However as Jonathan has pointed out, some better line-by-line parsing may be better. Scanning directly from stdin
this way isn't intuitive to the user.
How to check if user inputs are double in C?
As @SRhm mentioned in the comment section, you simply can use:
scanf("%lf %lf", &x, &y) == 2
to get two numbers from the user input.
A quote from scanf - C++ Reference explain the return value of the function:
On success, the function returns the number of items of the argument
list successfully filled.
scanf will return an integer representing the number of variables successfully read from the user input.
C# Validate input as double
You are on the right track with double.TryParse()
double abalbeginVal;
bool parsed = double.TryParse(aBalBeginS, out abalbeginVal);
if (parsed && abalbeginVal >=0.0)
{
// We're good
}
else
{
// Did not pass check
}
Float/Double type input validation in C#
You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
class Program
{
static void Main(string[] args)
{
double FahrenheitInput = 0;
double CelsiusInput = 0;
double KilogramInput = 0;
double PoundsInput = 0;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static double FahrenheitToCelsius(double INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double CelsiusToFahrenheit(double INPUT)
{
return INPUT * 1.8 + 32;
}
}
Trying to validate double as only numbers
To check the validity of the input, I would suggest utilizing stod() and exception handling. Because cin
takes as many expressions that can be interpreted to number as possible, and returns nonzero value if that happened. However, stod()
can check the number of characters that was parsed, and if we check whether whole expression is parsed, and if not, throw
, we can perform the validity check. Here's the modified getnumber():
double getNumber() {
double temperature;
bool got_the_value = false;
while (!got_the_value) {
try {
cout << "Please enter a temperature between -40 and 40 degrees Celsius: ";
string tmpstring;
cin >> tmpstring;
size_t pos;
temperature = stod(tmpstring,&pos);
if (tmpstring.size() != pos) {
cerr << "Bad value, try again..." << endl;
continue;
}
got_the_value = true;
}
catch (exception& e) {
cerr << "Bad value, try again..." << endl;
}
}
return temperature;
}
Validating a double in c++
This seems a close analog to your code that (mostly) works:
double GetDouble () {
double x;
cin >> x;
// ver1: while( cin.fail() ) // or !cin.good() no trailing char check.
while( cin.fail() || (cin.peek() != '\r' && cin.peek() != '\n'))
{
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while( cin.get() != '\n' ); // or cin.ignore(1000, '\n');
cin >> x;
}
return x;
}
Test to ensure the user input is a double and is greater than zero?
You're on the right track - you need to have a single while loop that gets the input and then tries both validations. One way to do this is to create a boolean value that tracks whether or not the value is valid, and then use that as the condition for the loop:
double outcome = 0;
bool valid = false;
while (!valid)
{
Console.WriteLine("Enter amount: ");
string inValue = Console.ReadLine();
if (double.TryParse(inValue, out outcome) == false)
{
Console.WriteLine("Initial value must be of the type double");
Console.WriteLine("\nPlease enter the number again: ");
}
else if (outcome < 0)
{
Console.WriteLine("Initial value must be of at least a value of zero");
Console.WriteLine("\nPlease enter the number again: ");
}
else
{
valid = true;
}
}
return outcome;
It's also possible to put both conditions in the while statement, but this approach lets you provide a different message depending on which conditions failed.
Related Topics
Error: Passing Xxx as 'This' Argument of Xxx Discards Qualifiers
Visual C++ Equivalent of Gcc'S _Attribute_ ((_Packed_))
Determine the Line of Code That Causes a Segmentation Fault
Are Flexible Array Members Valid in C++
Overload a C++ Function According to the Return Value
A Std::Map That Keep Track of the Order of Insertion
How to Pass a Member Function Pointer
How to Take the Address of a Function Defined in Standard Library
How to Convert a Double into a String in C++
Are "Anonymous Structs" Standard? And, Really, What *Are* They
Opengl - Index Buffers Difficulties
Enforcing Statement Order in C++