Floating point

• 12-04-2005
Flip
Floating point
Is it possible to check to see if a user has used a floating point number as of an integer?
• 12-04-2005
Dave_Sinkula
Take input as a string. Attempt to convert the string to an int. If it fails, try to convert it to a floating point value. If it is a value that could be either, such as "42", make your own rule for handling it.
• 12-04-2005
Flip
ok thank you i've done this soo far....

Code:

```int check_string(string x1){         unsigned int pos = x1.find(".",0);         int y = 0;         if(pos != string::npos){                 cout << "Invalid input! Conversion Failed"<<endl;                 y = 1;         }         return (y); }```
which is all dandy.... but how do i check if the string contains letters? because i need to convert it back to an integer
• 12-04-2005
Enahs
Code:

```#include <iostream> using namespace std; int main() {         double input;         cout << "Enter a number: ";         cin >> input;         if ( (input / static_cast<int>(input)) == 1)         {                        //Is int...do whatever         }         else {}         return 0; }```
• 12-04-2005
dwks
Or !isdigit(). (<cctype>)
• 12-04-2005
Dave_Sinkula
Code:

```#include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; // for homework and toy programs int main() {   ifstream file("file.txt");   string info;   while ( getline(file, info) )   {       istringstream iss(info);       char c;       float afloat;       if ( (iss >> afloat) && !iss.get(c) )       {         cout << " afloat = " << afloat << endl;       }   }   return 0; } /* file.txt abc 123 123.456 0x14 9a */ /* my output  afloat = 123  afloat = 123.456 */```
• 12-05-2005
Salem
Or use strtod() and see if there is a '.' between the start and end pointer (and check errno as well).
• 12-05-2005
Daved
A simple way to check the input straight from cin is to read into an int. If it succeeds, then the first characters of the input were numbers. Then check the next character in the stream to see if it is a newline (from the user hitting enter to send the input). If it isn't, then the input isn't valid because they entered a decimal point or a non-numeric character.
Code:

```int val = 0; while (!(cin >> val) || cin.get() != '\n') {   cin.clear();   cin.ignore(numeric_limits<streamsize>::max(), '\n');   // Invalid input! }```
The clear and ignore clean out the fail state and any and all bad characters.