0

I am having trouble understanding how to convert a 'char' to an 'int'. I created a temporary array to hold, and then bubble sorting it. (This is for an assignment)

The number I am trying to sort is in:

Item* m_items[MAX_NO_ITEMS];
char m_sku[MAX_SKU_LEN + 1];

that is why I am trying to convert it to an integer.

char* num[30];

for (int i = 0; i < m_noOfItems ; i++) {
    num[i] = m_items[i]->sku();
}

int i,x;

for (i = 1; i<m_noOfItems; ++i)
{
    for (x = 0; x<(m_noOfItems - i); ++x){
        if (num[x]-48 > num[x + 1]-48)     // This comparison
        {
            char* temp = num[x + 1];

            num[x + 1] = num[x];

            num[x] = temp;

            cout << num[x] << " > " << num[x+1] << endl;

        }
    }   
}

I am just trying to convert it to an integer so I can use " > " in the if statement above.

EDIT: I fixed it by changing num to const char*. Then making an integer array, using atoi() to store it to the new int array. (for future reference)...

John C
  • 517
  • 2
  • 6
  • 16
  • 1
    if you subtract 48 from both sides of the comparison it's the same as not subtracting anything. Also it's perfectly valid to compare to characters using `>` it will compare their ASCII values. – twain249 Apr 15 '17 at 01:39
  • you could use the `atoi()` function? – ScottishTapWater Apr 15 '17 at 02:41
  • @twain249: No, actually it's not the same as not subtracting anything. For signed integral types, the subtraction may cause undefined behavior, while direct comparison would not. And for unsigned types, the result of the comparison may be different. A fairly common trap is that if you want to check elapsed time, you *must* write it as `if (time2 - time1 > threshold)` because `if (time2 > time1 + threshold)` is an incorrect test even though it only added `time1` to both sides. **Modular arithmetic does not obey the rules of grade school arithmetic.** – Ben Voigt Apr 17 '17 at 00:13
  • Important related note, it is unspecified whether `char` is a signed or unsigned type. – Ben Voigt Apr 17 '17 at 00:13

0 Answers0