Invalidating non numeric input entries

Hi,

This is one of my first lab assignments. I was to create a very simple program to asks for the temperature in celsius which the program would convert to fahrenheit, and then vice versa. With the option to either go again or exit the program.
I managed to do that successfully, but I was also instructed to put in a code to keep the program from crashing if the user typed a character instead of a integer. I been trying for days to use all kinds of codes or hints I found online but I just can't seem to get it right and working. Below is my code, any help or what to do or where I can get the information needed to complete this, would be appreciated.

Thanks,
Milton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  #include <iostream>
#include <conio.h>
#include <cctype>
#include <sstream>
#include <ios>
#include <limits>


using namespace std;

int main()
{
	do
	{
		float fahrenheit;
		
		int celsius;

		cout << "Enter a temperature in Celsius: ";

		cin >> celsius; // Displays integer entered

		fahrenheit = (celsius * 9.0) / 5.0 + 32; //Conversion formula

		cout << "The temperature in Fahrenheit is : " << fahrenheit   << endl; //Display conversion


		cout << "Enter a temperature in Fahrenheit : ";

		cin >> fahrenheit; // Display integer entered

		celsius = (fahrenheit * 5.0) / 9.0 - 32; //Conversion formula

		cout << "The temperature in Celsius in : " << celsius << endl; //Display conversion

		{
			cout << " fahrenheit " << celsius + 1 << " : ";
			while (!(cin >> celsius)) {
				cin.clear(); // reset input
				while (cin.get() != '\n')
					continue; //get rid of bad input
				cout << "Please enter a number: ";
			}


			
			cout << "\nGo again (Y/N)?\n"; //Ask Y or N to continue or exit

	}while (toupper(_getch()) != 'N'); //Exits program on hitting N

	return 0;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
    int number ;

    while( std::cout << "please enter a number: " )
    {
        if( std::cin >> number ) break ; // a number was entered; exit the loop

        std::cin.clear() ; // clear the failed state
        std::cin.ignore( 1000, '\n' ) ; // throw away the non-numeric input
        std::cout << "error in input, please try again\n" ;
    }

    std::cout << "you entered " << number << '\n' ;
}
Use char as your var that will be inputted, then check if the variable is a number, finally convert that var to float or int

1
2
3
char x;int celcius;
cin>>x;
if(isdigit(x))celcius=atoi(x)
Last edited on
Thank you
Topic archived. No new replies allowed.