I'm having difficulty understanding typecasting, and i am attempting to improve my understanding by assigning the contents of a string
to an array of unsigned chars
. I expected the code below to print true
, but it does not.
unsigned char a[10]={0,1,2,3,4,5,6,7,8,9};
string b="5";
if(a[5]==(unsigned char)atoi(b.c_str())){
cout<<true<<endl;
}
What am I missing?
Your sample code has either one or several problems with it if you are attempting to print out
true
. How many depends on how you're trying to do that. My first two points apply if you are comparing text to other text. If you're trying to convert text to a number and compare numbers, ignore them.1) While this will produce an array of unsigned characters, they won't be text values. The values in that array are the first 10 ASCII characters rather than the characters that produce '0' through '9' when printed. Those characters can be placed in your array with the code:
Again, this is only provided you're trying to compare text data. If you're trying to convert to a number and compare the entries in this array with that number, you'll want your original array.
2) You are correct that
a[5]
will access the sixth element ofa
. If you are comparing text values and not numeric values, you need only to access the first element of your string for comparison. This is provided you know the string is at least 1 element in size. Since you defined it just above this code, that's fine, but in cases of user input, you'll need to check. The proper syntax for this comparison, again as deviantfan stated, isa[5] == b[0]
, because the[]
operator onstrings
will return achar
.Once again, the above applies to your answer only if you're comparing text values. If you're comparing numeric values, your original code is correct.
3) You haven't placed quotation marks around the
true
. While this will compile, and even print something--it won't betrue
unless a few conditions are met that you're unlikely to encounter this early in your coding career. What you likely meant to put is "true", which will make the output print true. Also, you wantcout
, notcount
.Here is a link to an example which compares the string and the (modified) character array, as text data. If you're comparing numeric data, the only thing wrong with your code is 3).