Using an If statement how could I go about detecting a decimal enter by the user?
Basically I am writing a program that prompts the user to enter the month and date and I want to be able to send a warning message if a decimal point is used.
Using an If statement how could I go about detecting a decimal enter by the user?
Basically I am writing a program that prompts the user to enter the month and date and I want to be able to send a warning message if a decimal point is used.
Correct me if I'm wrong because I am new to C++, but if you declare and integer type, any number assigned to the variable will automatically be truncated into an integer.
Example:
If you input 3.14159, it should output 3, but I'd be more confident if a more experience coder agreed with meCode:#include <iostream> using namespace std; int main{ int a; cout<<"Enter a decimal number: "; cin>>a; cout<<a; return 0; }
- Grady (:
That's right. But I think he's referring to character array input. In that case:
Code:loop infinite: un-set a flag; get input; loop < length: if string[index] is a '.' { - tell user that you have an annoying non-user-friendly program much like DOS which doesn't intelligently handle these things; - set a flag; } :end loop if flag isn't set { jump out of loop; } :end infinite
Code:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 0; }
Ok this is how I figured it out.Code:#include <iostream.h> int main() { int month, day; cout << "Enter a month (use a 1 for Jan, ect.): "; cin >> month; cout << "Enter a day of the month: "; cin >> day; if (month < 1 || month > 12 || month == '.' ) cout << "An incorrect month was entered" << endl; else cout << "The month number is " << month << endl; if (day < 1 || day > 31 || day == '.') cout << "An incorrect date was entered" << endl; else cout << "The date number is " << day << endl; return 0; }
Intresting code Sebastiani. I have gotten into loops yets. My fav part is "non-user-friendly program much like DOS which doesn't intelligently handle these things;
"
Maybe you can use this...
if you read an integer
Is that what you meanCode:int x; cin >> x; if ( cin.good() ) //this is to check if the value entered in an integer ( has no decimals )
you could use
getline(cin,string,'.')
and the read would end at the decimal
then you could check the string length and use an if statement if i's too short.
--Cid666
Here's a mighty easy way to check if a variable has any decimal points...
As for "if (month < 1 || month > 12 || month == '.' )", it's pretty pointless to test for '.', as you'll fail on one of the other tests if '.' is entered anyway.Code:#include <cmath> // ... if (std::floor(choice) == choice) { // No decimal } else { // Decimal }