Hello, I recently started a c++ class, and one of the assignments is that we need to create a c++ program which converts Fahrenheit to Celsius. I have succeeded into doing just that, but I need to validate user input's values, meaning that the program must reject any entries that contains letters, and when it finally accepts the entry, it still does the calculations(the function is executed). Does anyone know how to do this? Any help is appreciated:

#include <iostream>
#include <iomanip>

using namespace std;

float FahrenheitToCelsius(float);
int main()
{
    float fahrenheit;
    int choice;
	char input[10];
    do{

    cout << "This program converts fahrenheit to celsius" << endl << endl ;
	
    cout << "Please Enter Fahrenheit Degrees: ";
    cin >> fahrenheit;
	while (fahrenheit = !isdigit){
		cin.clear();
		fflush(stdin);
		cout <<"error";
		cin >> fahrenheit;
		
	}

    cout << "Your Conversion Is: "<< fahrenheit << " Degree Fahrenheit to:" << endl;
    cout << FahrenheitToCelsius(fahrenheit)<< fixed << setprecision(2) <<" Degrees Celsius.";
    cout << "Want To Play Again?";
    cout << "1 == Yes";
    cout << "2 == No " << endl;
    cin >> choice;

    } while (choice == 1);

    cin.get();
    return 0;
}

float FahrenheitToCelsius(float fahrenheit)
{
    return fahrenheit = (5.0/9.0) * (fahrenheit - 32);
}

Recommended Answers

All 2 Replies

I would get the input data as a string, then check each character to see that it is a numeric digit 0-9 or a . for floats (and there can be only one dot in the string). If it passes that test then convert the string to a float.

Did you not already have a thread for this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.