In: Computer Science
Using c++
Im trying to figure out a good user validation for this loop. So that if a valid number is not input, it gives an error message. I have the error message printing but its creates an infinite loop. Need some help.
double get_fahrenheit(double c){
double f;
f = (c * 9.0) / 5.0 + 32;
return f;
}
#include "question2.h"
#include<iostream>
#include<string>
using std::cout; using std::cin; using std::string;
int main()
{
double c;
double f;
double user_exit = 444;
do{
cout<<"Enter Celsius (Enter 444 to exit)\n";
cin>>c;
if(cin.good()){
f = get_fahrenheit(c);
cout<<c<<" degrees celsius is "<<f<<" degrees fahrenheit. \n\n";
break;
}else {
cout<<"Invalid Input! Please input a numerical value. \n";
cin.clear();
}
}while(c != user_exit);
cout<<"Goodbye!";
return 0;
}
i hope this will solve the above problem ... i like would be helpful... comment if any thing goes wrong...
Code:
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
double c;
double get_fahrenheit(double c)
{
double f;
f = (c * 9.0) / 5.0 + 32;
return f;
}
int digit(string str)
{
string dot=".";
int len = str.size(), j = 0,pos;
for (int i = 0; i < len; i++)
{
if
(isdigit(str[i]))
{
continue;
}
else
if(str.find('.')!=pos){
j++;
if(j>1)
return 0;
}
else
{
return 0;
}
}
c = stod(str);
return 1;
}
double check(string str)
{
c = stod(str);
}
int main()
{
string str;
int ch;
double f;
double user_exit = 444;
do
{
cout << "Enter
Celsius (Enter 444 to exit)\n";
cin >> str;
ch=digit(str);
if (c==user_exit)
{
break;
}
else if (ch == 1)
{
f = get_fahrenheit(c);
cout << c << " degrees celsius is " << f <<
" degrees fahrenheit. \n\n";
}
else
{
cout << "Invalid Input! Please input a numerical value.
\n";
}
}while (c != user_exit);
cout << "Goodbye!";
return 0;
}
Output:
Enter Celsius (Enter 444 to exit)
rock
Invalid Input! Please input a numerical value.
Enter Celsius (Enter 444 to exit)
55
55 degrees celsius is 131 degrees fahrenheit.
Enter Celsius (Enter 444 to exit)
55.5
55.5 degrees celsius is 131.9 degrees fahrenheit.
Enter Celsius (Enter 444 to exit)
444
Goodbye!