|
-
February 17th, 2011, 07:53 AM
#1
input validation error
Hello again,
I had to write for this assignment and my program works, my professor doesn't care about validating input, however, I do. I can't figure out for the life of me why using an if/else only will validate once. After that, if you keep putting in wrong choices the program goes all to hell. Should I use a while loop somehow? I don't know how to get it to ask indefinitely - or I just can't remember (I think I did this before, last semester.) This isn't towards my grade, just my understanding... I like validating. Makes stuff stupid-proof.
Code:
/***************************\
| Degree Converter |
| Code By: Ben Brotsker |
| Last Mod: 02/16/11 |
\***************************/
#include <iostream>
#include <iomanip>
using namespace std;
float C_to_F();
float F_to_C();
int main()
{
char rerun;
//program intro
cout << "This program converts temperatures between Celcius and Farenheit." << endl
<< "Would you like to run this program? (Y/N): ";
cin >> rerun;
system("cls");
int choice;
float degree = 0;
while (rerun == 'y' || rerun == 'Y')
{
//--MENU--//
cout << "DEGREE CONVERTER" << endl
<< "------------------------------------------------"
<< endl << endl
<< "Which conversion would you like to perform?" << endl
<< "1: Farenheit to Celcius" << endl
<< "2: Celcius to Farenheit"
<< endl << endl
<< "Enter your choice: ";
cin >> choice;
//validate user input
if (choice == 1 || choice == 2)
{
//menu choices
switch (choice)
{
case 1:
degree = F_to_C();
break;
case 2:
degree = C_to_F();
break;
default:
cout << "Input Error! Please restart program!" << endl;
}
}
else
{
cout << "Please re-enter your choice: ";
cin >> choice;
}
//output result
cout << setprecision(4);
if (choice == 1)
cout << "The temperature in Celcius is " << degree << " degrees." << endl;
else
cout << "The temperature in Farenheit is " << degree << " degrees." << endl;
cout << "Would you like to covert another temperature? (Y/N): ";
cin >> rerun;
system("cls");
}
system("cls");
cout << "Have a nice day!" << endl;
return 0;
}
//--FUNCTION DEFINITIONS--//
float F_to_C()
{
float Fdeg;
float Cdeg;
cout << endl
<< "Please enter the degrees in Farenheit to be converted: ";
cin >> Fdeg;
Cdeg = (Fdeg-32)*0.5556;
return Cdeg;
}
float C_to_F()
{
float Fdeg;
float Cdeg;
cout << endl
<< "Please enter the degrees in Celcius to be converted: ";
cin >> Cdeg;
Fdeg = (Cdeg*1.8)+32;
return Fdeg;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|