I'm trying to write a function that takes a hexidecimal value in string-form as an argument and coverts it into a decimal value. I haven't started writing error code yet, but even accepting an argument which shouldn't cause an error causes the command prompt to crash. What's wrong with this code?
Although this would be a lovely piece of syntactic sugar if C++ allowed this to work as you're probably intending it to... sadly, this likely doesn't do what you think it does.
The whole right side of these expression will always evaluate to true. The left side will also always evaluate to true UNLESS the character at i is a null character (0x0).
You may wish to check instead if the character at i is greater than or equal to a certain character AND less than or equal to a certain character. Remember, all character literals have integer values. There is also the std::isdigit(char) function in <cctype> for the first statement.
That's how my code was written before and it wasn't working... Hrmm
It's changed back.
1 2 3 4 5 6 7 8 9 10 11 12 13
for(int i = 0; i<=hexString.length()-1; i++) //string position loop
{
if(hexString.at(i) <= '9') //character comparison
{
decValue[i] = hexString.at(i)-'0'; //sets decValue[i] to value of digit character
}
if(hexString.at(i) >= 'A' && hexString.at(i) <= 'F') //character comparison
{
decValue[i] = hexString.at(i)-'0'-7; //sets decValue[i] to value of letter character in decimal
}
exponentCounter[i] = temp--;
}
Interesting. There were some small logic errors, but mostly the issue right now is that it crashes if I put it in a function, but if the code in in int main() it works fine... Why is this?
You never allocate memory for your exponentCounter pointer (on line 10 of your original code), and that pointer is uninitialized and not guaranteed to point to memory that you have access to. Thus, you open up a major risk for a segfault and the program's behavior is undefined.
You can either new an array once you know the length of hexString (make sure to delete what you new) or use an STL container like std::vector to store your data.
I understand, but I'm not sure what it's supposed to be initialized as.... Honestly, when I say "confused" I mean totally very quite completely so I'm afraid.
A reference is like a pointer that you don't have to dereference but you can't reassign. That reference needs to point to something... so why not make it initialize it with the erroneous string variable that you're passing into your constructor?
EDIT: I just noticed that the constructor takes a const string& while the private member is a plain string&. You're going to need to decide which approach to take.
The exception object needs to make a copy of the string.
When an exception is thrown (as in throw hexException(hexString);), the function scope is exited and all local objects (including the string hexString) are destroyed. Without a copy, the exception object would hold a dangling reference to a string that has been destroyed.