The goal is to write program asking for the user for a float, and to put in safety nets against in-proper entries.
The following code allows the user to enter both positive and negative integers and floats, but the program won't give the error message for certain types of input errors.
92.64.47 will be displayed as 92.64
864hj will be displayed as 864.
Whenever the code reaches an error in having the input be an integer or float, it doesn't give an error message, it just stops the string right there.
Suggestions on where/what my problem is and how I might fix it?
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
float myFloat;
char myStr[30];
bool validData;
int i, len /* length of string */;
do
{
cout << "Enter a float number: ";
cin.getline(myStr,30);
validData = true;
len = strlen(myStr);
i=0;
while ((i < len) && (validData == true))
{
if ((i == 0) && ((myStr[i] < '0') || (myStr[i] > '9')) && (myStr[i] != '-') && (myStr[i] != '.')) //allows for +- integers and floats
{
cout << "if loop checking\n";
validData = false;
cout << "if loop checked\n";
}
i++;
}
if (validData == true)
{
myFloat = atof(myStr);
cout << "Your float is: " << myFloat << "\n";
}
else
{
cout << "Incorrect Data. Try again!!!\n";
}
} while (validData == false);
return 0;
}