|
 |
|
 |
07-09-2002, 02:06 AM
|
#1 (permalink)
|
|
Registered User
Join Date: Jul 2002
Location: Dallas, TX
Posts: 2
|
checking datatypes in c++
How do I check that the correct input was given for a certain datatype? For example, I declare an int var "i" and want to make sure the input for this var is actually a number before the rest of the program continues?
Last edited by brtklt; 07-09-2002 at 03:16 AM.
|
|
|
07-09-2002, 11:30 PM
|
#2 (permalink)
|
|
Newbie
Join Date: Jun 2002
Location: Denmark
Posts: 1,696
|
Code:
int main()
{
int i;
cout << Please enter an integer: ;
cout.flush();
cin >> i;
if(i > 0)
cout << "Thanks for giving me an integer" <<endl;
else
cout << "What, are you dumb or just stupid? I said an integer... Dumba**" <<endl;
return i;
}
|
|
|
07-09-2002, 11:37 PM
|
#3 (permalink)
|
|
Registered User
Join Date: Jul 2002
Location: Dallas, TX
Posts: 2
|
Simple enough...
|
|
|
07-09-2002, 11:46 PM
|
#4 (permalink)
|
|
Newbie
Join Date: Jun 2002
Location: Denmark
Posts: 1,696
|
If I remember correct, the cin class will set a given int type to 0 if the input isn't recognised as the same type.
Naturaly inputting to a string, will just convert the input of 123 to the string "123"
But this will be done for int and float/double inputs.
|
|
|
07-10-2002, 12:54 AM
|
#5 (permalink)
|
|
Newbie
Join Date: Jun 2002
Location: Denmark
Posts: 1,696
|
This is missleading... But I guess C++ is ugly that way..
A small test revealed, if the input isn't an int, the int value will be set to less than INT_MIN/2 So the disturbing part is, what if the user chose to input INT_MIN+2 then we can't be sure wether its a valid input or not... Not even errno is set to anything..
Oddly enough, theres alot of setf() flags, that can turn input into truely boolean or decimal but none defined for a simple int...
Guess the last thing todo, is use a fscanf() on stdin, to make sure its a valid int you're getting..
|
|
|
07-10-2002, 03:57 AM
|
#6 (permalink)
|
|
Newbie
Join Date: Jun 2002
Location: Denmark
Posts: 1,696
|
There is a fix, buts thats just a small hack I came up with...
Code:
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int i=INT_MIN;
cout << "Enter your digit: ";
cout.flush();
cin >> i;
if(i > INT_MIN)
cout << "Thanks for the integer." << endl;
else
cout << "WTF. No integer?" << endl;
return i;
}
But, then again, if the user inputs a value repressenting INT_MIN (which on 32bit architecture is -2147483648 ) it will fail.. Yet, who would want to use that as the input value?
|
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
All times are GMT -8. The time now is 09:59 PM.
|
Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
|
 |
|