Home > Enterprise >  How to write a function that receives a string as a parameter and returns the maximum digit that app
How to write a function that receives a string as a parameter and returns the maximum digit that app

Time:12-25

These are the details. (https://i.stack.imgur.com/cMY9J.png)

#include <stdio.h>
#include <stdlib.h>
int maxdigit(char sir[]);
int main()
{
    char s[100];
    gets(s);
    printf("The greatest digits is %i\n", maxdigit(s));
}
int maxdigit(char sir[])
{
    int i, max = 0;
    for(i=0;i<100;i  )
    {
        if(max<sir[i])
        {
            max = sir[i];
        }
    }
    return max;
}

I genuinely don't know how to get only the integer values in a string to return it. How can i do it so it doesn't compare with the ascii codes of the letters?

CodePudding user response:

A few problems here:

  1. gets() is a dangerous function (since it can lead to buffer overflows), and has been removed from the C standard. Consider using fgets() or scanf().
  2. Your code assumes that all 100 digits have been entered by the user. If they enter less than 100, the memory for the other digits is uninitialised, and will probably be full of garbage. You need to stop when you reach the '\0' that terminates the string.
  3. To convert an ASCII code (for a digit) to the value of the digit, subtract '0' from it. But you'll need to ensure that all the entered digits are actually digits, maybe with isdigit().

CodePudding user response:

  1. Iterate until null terminating character. In your code you go beyond end of the string if the string length is smaller than the array
  2. Convert char representation of the digit to its integer value by substracting 0.
unsigned maxdigit(const char *str)
{
    unsigned max = 0;
    if(str)
    {
        while(*str)
        {
            if(isdigit((unsigned char)*str))
            {
                if(max < *str - '0') max = *str - '0';
            }
            str  ;
        }
    }
    return max;
}
  • Related