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
unsignedlonglong highest_number(char* string, unsignedlonglong size)
{
unsignedlonglong max = 0;
for(unsignedlonglong 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>.
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: