0

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?

  • [Why is the `gets` function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/2505965) Your assignment's test example uses `fgets`; you should also use `fgets`. – Oka Dec 24 '22 at 19:58
  • Why don't you use the host environment's facilities to hand you input from `argv`, instead of creating a buffer? – Neil Dec 24 '22 at 20:47

2 Answers2

1

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().
pmacfarlane
  • 3,057
  • 1
  • 7
  • 24
0
  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;
}
0___________
  • 60,014
  • 4
  • 34
  • 74