Hello,
I have a quick question to ask...let's say I'm accepting user input with getche() and placing the input in a char...then I'm trying to convert the char digit into a numerical digit...is there any way to do that?
Hello,
I have a quick question to ask...let's say I'm accepting user input with getche() and placing the input in a char...then I'm trying to convert the char digit into a numerical digit...is there any way to do that?
Yep.
C way: (int)YourVariable.
C++ way: static_cast<int>(YourVariable)
thanks for the info lith...I'll see what I can do with it...much appreciated Chap
One of your major problems is that the char will only hold one # of a number like 15, and read in the 1 and 5 seperately. It's impossible to defeat your while() loop like that.
Ok. I'm going to rewrite your function to be standard (read: portable). conio isn't available to all compilers.
See if this code makes sense to you..
Code:#include <iostream> int main() { char chNumber[2]; // We need this to handle numbers in the more-than-single digit range. Otherwise your while loop will loop forever. while (1) // Loop forever.. we handle invalid numbers below. { std::cout << "Enter a number: "; std::cin >> chNumber; if ((chNumber[1] != '\0') || (chNumber[0] < '0') || (chNumber[0] > '9')) // If, for some reason, the number is invalid.. { std::cout << "\nInvalid number."; // Tell them, and.. break; // Quit the while loop. } std::cout << "\nASCII number is: " << static_cast<int>(chNumber[0]) << "\n\n"; // Else print the ASCII value. } std::cin.ignore(80, '\n'); std::cin.get(); return(0); }
Last edited by Lithorien; 03-09-2005 at 08:02 PM.
>>then I'm trying to convert the char digit into a numerical digit
Not sure if your problem's been solved already or not, but if you're trying to convert '9' into the integer 9, then what you want is:
int theDigit = theChar - '0';
Cheers
**EDIT**
If I'm not mistaken, if chNumber[1] != '\0' then you've already got an index out-of-bounds error. A better solution would probably be to use std::getline() to read into a std::string first, and then check to see if the size is greater than 1. Then, the testing for chNumber[0] < '0' etc. can be replaced by std::isdigit(), which is found in <cctype>.Code:#include <cctype> //(chNumber[1] != '\0') || (chNumber[0] < '0') || (chNumber[0] > '9') //Replace with: std::isdigit(chNumber[0])
Last edited by Hunter2; 03-09-2005 at 09:51 PM.
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.
Nice and elegant fix, Hunter.
I was going the string route, but just wasn't sure how to handle it. Thanks!