The program bellow is supposed to do two things. First is to reverse a string and the second is to find in that string the most and the least seen character. It works almost fine. The results are correct but on finishing it does not return 0 and second if I delete the line 16 puts("\n")
the program does not work. That specific line obviously does nothing, but without it, it does not work. I tried to replace it with fflush(stdin)
but it did not work. I do not get it. What is wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
void chars(char *s, char *most_seen, char *less_seen)
{
int letters[26] = {};
for (int i = 0; i < strlen(s); i++)
{
char c = *(s + i);
letters[(int)c - 97]++;
}
puts("\n");
int maxLetter = 0;
int minLetter = 0;
int posMax = 0, posMin = 0;
for (int i = 0; i < strlen(s); i++)
{
if (letters[i] > maxLetter)
{
maxLetter = letters[i];
posMax = i;
}
if (letters[i] < minLetter)
{
if (letters[i] == 0) continue;
minLetter = letters[i];
posMin = i;
}
}
*most_seen = posMax + 97;
*less_seen = posMin + 97;
}
char *reverse(char *s)
{
char *reversed = (char *)malloc(strlen(s) * sizeof(char));
fflush(stdin);
int i = 0, size = strlen(s) - 1;
for (; i < strlen(s); i++)
reversed[i] = s[size--];
reversed[i] = '\0';
return reversed;
}
int main()
{
char *s = malloc(1000 * sizeof(char));
char *s2;
char mostSeen, lessSeen;
gets(s);
chars(s, &mostSeen, &lessSeen);
s2 = reverse(s);
printf("%s\n", s);
printf("%s\n", s2);
printf("%c %c\n", mostSeen, lessSeen);
free(s);
free(s2);
return 0;
}