Is it possible to check to see if a user has used a floating point number as of an integer?
Is it possible to check to see if a user has used a floating point number as of an integer?
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.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
ok thank you i've done this soo far....
which is all dandy.... but how do i check if the string contains letters? because i need to convert it back to an integerCode: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); }
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; }
Last edited by Enahs; 12-04-2005 at 03:06 PM.
Or !isdigit(). (<cctype>)
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
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 */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Or use strtod() and see if there is a '.' between the start and end pointer (and check errno as well).
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.The clear and ignore clean out the fail state and any and all bad characters.Code:int val = 0; while (!(cin >> val) || cin.get() != '\n') { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Invalid input! }