-
Restricting data types?
Hi,
I'm new to programming and need some help with a program i wrote.
I have written the program as follows:
Code:
#include <iostream>
using namespace std;
double ftoc ( double f );
int main()
{
double f; double c;
for ( int y = 1; y != 0 && y == 1; y )
{
cout<<"Enter degrees in Fahrenheit: ";
cin>> f;
cin.ignore();
cout<< f <<" degrees Fahrenheit is "<< ftoc ( f ) <<" degrees Celsius\n\n";
cout<<"Do you want to convert again (yes = 1,no = 0): ";
cin>> y;
cin.ignore();
while ( y != 1 && y != 0 )
{
cout<<"You need to enter either a 1 or 0\n\n";
cout<<"Do you want to convert again (yes = 1,no = 0): ";
cin>> y;
cin.ignore();
}
cout<<"\n";
}
}
double ftoc ( double f )
{
return (5.0/9.0)* (f - 32.0);
}
I noticed that when my program asks to enter in the degrees fahrenheit, if you enter in anything other than a number it goes into an infinite loop. Now, I want to protect against this by adding a loop asking to enter a number, but how do I go about doing this? I assume you would have to restrict data types, but I'm not sure how that is done.
Also another question I have is if its possible to insert a degree symbol in the program? If so, then how do you insert it?
Any help is appreciated.
Thanks
-
Code:
double f;
while (!(cin >> f))
{
cin.clear();
cin.ignore(1000, '\n');
// Prompt about the bad input and ask for input again.
}
If you also want to error out when the user types some good input followed by bad input (e.g. "76.4 is the answer\n"), then this code will do that:
Code:
double f;
while (!(cin >> f) || cin.get() != '\n')
{
cin.clear();
cin.ignore(1000, '\n');
// Prompt about the bad input and ask for input again.
}
>> possible to insert a degree symbol in the program?
Perhaps:
Code:
cout << 'º'; // alt-167