Compare two values of char array
I am programming in C and I have a character array filled with letters/numbers. I want to compare the first two values together as one number or combo.
char values[8];
//a value of this might be 245756
switch (values[0 and 1]){
   case 24:
     do something;
   case 45:
     do something else;
}
Do I have to concatenate or what if I want to combine the two values and then see if they equal some set of 开发者_如何学Ccombinations?
Thanks!
Please let me know if I am being unclear.
I'm assuming that your char array holds the characters '2', '4', etc.
In which case, you can convert a character to its equivalent integer value as follows:
char x = '2';
int  y = x - '0';
So all you need to do is perform this calculation for each of values[0] and values[1], and then perform the base-10 maths to combine these into a single integer value.
If your char array already holds the integer value for each digit, then you can of course skip the conversion, and jump straight to the base-10 maths.
switch ((values[0] - '0') * 10 + (values[1] - '0')]){
you can do the switch based on the following expression:
(values[0]-'0')*10 + values[1]-'0'
One way to do this would be to cast the array to a uint16_t pointer and dereference it (some people might disapprove of this on principle, though). You'd have to determine what numbers (as a two byte int) the combinations would form to set your case values, though. For example,
switch (*(uint16_t *)values) {
    case 0x4131: {    /* "1A" on little-endian systems */
  ...
Another way would be to form an int from the two characters in a simple expression and switch on it.
switch( ((int)values[0] << 8) | (int)values[1] ) {
    case ('1' << 8) | 'A': {
  ...
The ('1' << 8) | 'A' is ok for case since it can be evaluated at compile time.
char values[8]="0123456";
switch ( (values[2]=0,atoi(values)) ){
   case 24:
     do something;
   case 45:
     do something else;
}
should work
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论