This was a challenge off of Codewars. The function takes a string as an argument and it returns a string that is in the fraction format. If the input characters are between 'a' and 'm' it is supposed to be an 'error free' status, otherwise it is an error message.
example: aaab
should return 0/4
where the numerator is the amount of error codes and the denominator is the string length minus the leading NULL character.
xxa
would return 2/3
.
The question I have is how do I put an integer into a char array? As you will see I am adding a '0'
to the integer which works for numbers 0-9 but for bigger numbers it prints other characters.
I'm using Xcode as my IDE.
Here's the code:
#include <stdio.h>
#include <string.h>
char* printerError(char *s)
{
int i, string_size, error_total;
unsigned long int size = strlen(s);
char status[3];
char *ptr;
string_size = error_total = 0;
for (i=0; i<size; i++)
{
if (s[i] != '\0' && s[i] != EOF)
{
string_size++;
if (s[i] > 'm')
error_total++;
}
}
status[0] = error_total + '0';
status[1] = '/';
status[2] = string_size + '0';
ptr = status;
printf("%s\n", status);
return ptr;
}
int main(void) {
printf("error code: %s\n", printerError("aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbmmmmmmmmmmmmmmmmmmmxyz"));
return 0;
}