find the highest digit

I can't find the highest digit within c-string.
could anyone please help finding my mistake?
if the user was to enter 1234. the highest shall be 4 but can't get that number.
Any ideas would be appreciated.
Thanks.


int Hnum(char* str)
{
// int size = 0;
int H = 0, remainder, div =0;
int intstr = atoi(str);
//while (*str != '\0')0
for (int size = 0; size < sizeof(str); size++)
{
remainder = str[size] % 10;
div = str[size] / 10;
if (remainder > div)
{
H = remainder;
}
// *str = *str / 10;
//size++;
str++;
}
return H;
*/



}
The easiest way to find the highest char (or any other structure) is:
1
2
3
4
5
6
7
8
9
unsigned long long highest_number(char* string, unsigned long long size)
{
    unsigned long long max = 0;
    for(unsigned long long index = 0; index < size; index++)
    {
        if(string[max] < string[index]) max = index;
    }
    return max;
}

The problem is: the sizeof operator is compile-only. You must use a container which stores the size of the string (the allocated memory). The best one is the std::string structure from <string>.

iQChange
Last edited on
Please use code tags when posting code. Highlight the code then select "<>" from the format menu at right. Here's your code again:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int Hnum(char* str)
{
    // int size = 0;
    int H = 0, remainder, div =0;
    int intstr = atoi(str);
    //while (*str != '\0')0
    for (int size = 0; size < sizeof(str); size++)
    {
        remainder = str[size] % 10;
        div = str[size] / 10;
        if (remainder > div)
        {
            H = remainder;
        }
        // *str = *str / 10;
        //size++;
        str++;
    }
    return H;
}


It looks like you've gone back and forth between comparing the digits in str vs. converting it to a number and comparing the digits of the number. Since the string already has the individual digits it's easiest to just use the string. In otherwords, inside the loop you will do:
if (str[i] > max) max = str[i];


At line 7 sizeof(str) gives the size of the str variable (the pointer), not the size of the data that it points to. For a null-terminated string, you would use strlen() for that. But in this case you don't need to: just go until you reach the end:
1
2
3
for (size_t i=0; str[i]; ++i) {
    ...
}


Hope this helps,
Dave
Topic archived. No new replies allowed.