I got an assignment where it's optional requirements require me to convert x(real number) from degree to radian if the user's input has the word 'degree' appended at the end(example: sin 30 degree will be automatically converted to sin 0.523599). If the word 'degree' is absent from the input, no conversion is required.
How can i do this in C++
I had tried this way:
#define PI 3.14159265
string check;
If(check.empty())
number = number;
Else if(!check.empty && check == "degree")
number = number*PI/180;
Then using some calculation coding the program will display the answer appropriately (example coding: sin (number);)
But these way doesn't seem to works as intended.
How should i do it?
#include <iostream>
#include <string>
#include <cctype>
#include <cmath>
int main()
{
std::string fn_name ;
double number ;
if( std::cin >> fn_name && std::cin >> number )
{
// skip characters in the input buffer till a new line
// or a non-white-space character is extracted
char c ;
while( std::cin.get(c) && c != '\n' && std::isspace(c) ) ;
if( c != '\n' ) // if it is not a new line
{
// put the non-white-space character back into the input buffer
std::cin.putback(c) ;
// read it in as a string
std::string deg ;
std::cin >> deg ;
if( deg == "degrees" )
{
// convert number from degrees to radians
staticconstexprdouble pi = 3.1415926535897932385 ;
std::cout << number << " degrees == " ;
number *= pi / 180 ;
std::cout << number << " radians\n" ;
}
}
std::cout << fn_name << '(' << number << ") == " ;
if( fn_name == "sin" ) std::cout << std::sin(number) << '\n' ;
// etc
}
}
Or read the entire input as a single string. Then use a stringstream to parse it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
string input;
cout << "Enter your input:\n";
getline(cin, input);
string name, units;
double value;
istringstream ss(input);
if (ss >> name >> value)
{
if (ss >> units && units == "degree")
{
value = value * PI / 180.0;
}
if (name == "sin")
cout << sin(value) << '\n';
}
(requires #include <sstream> to use stringstream).