d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > N) Help C++ Just Numbers > Cin
Add Reply New Topic New Poll
Member
Posts: 6,279
Joined: Jan 18 2007
Gold: Locked
Jun 14 2012 05:27am
Hi

i need some help

i wanna have the cin function which just scans a number and not a letter

if i tip a letter i need a cout something like << " thats not a number"

maybe some help ?

greetz
Neme

Member
Posts: 827
Joined: Jan 16 2012
Gold: 0.00
Warn: 10%
Jun 14 2012 09:00am
"According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f will be true only if f is NaN." ( took from stackoverflow )

so i guess you could use:

Code


int void()
{
   bool check = true;
   string input;
   int n;

   while(check)
   {
         cout << "Input a number:";
         cin >> input;
 
         if(input != input)
        {
               cout << "Not a number, try again";
        }
        else
        {
               n = (int)input;
               check = false;
    }
}

Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Jun 14 2012 08:46pm
isn't there a function to check if it's a digit? or check the unicode/ascii values?
Member
Posts: 13,425
Joined: Sep 29 2007
Gold: 0.00
Warn: 20%
Jun 14 2012 11:46pm
Quote (carteblanche @ Jun 14 2012 10:46pm)
isn't there a function to check if it's a digit? or check the unicode/ascii values?


wouldnt be that hard.

if you need to see if its a digit just check if the character ranges between (int)48 - 57 or w/e and if you need to turn it into its actual value just minus 48 from its character value.
Member
Posts: 3,514
Joined: Feb 12 2006
Gold: 2,747.00
Jun 15 2012 08:56am
Just use scanf() from stdio.h

Example:

Code
int x;

printf("Type a number: ");

if(scanf("%d", &x))
printf("You typed %d\n", x);
else
printf("You didn't type a number.\n");


More about scanf() here: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

The whole site is very helpful when writing C/C++

Edit: Fixed a typo

This post was edited by Jupelius on Jun 15 2012 08:58am
Member
Posts: 9,803
Joined: Jun 28 2005
Gold: 6.67
Jun 15 2012 10:15am
@StormHasHe: It would be better if you didn't offer advice on topics you clearly have no idea about.

In C++03, it's not that straightforward, the best idea I came up with is http://ideone.com/EJ7LQ

If you can use C++11, you can use functions like stoi and get something like this http://ideone.com/47LGS

I admit, neither is very reader-friendly, but it'd be trivial to write your own template function that'd try to convert strings from an istream.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll