Reputation: 270
I have been implemnting an algorithim for counting and printing duplicate letters (two times or more) in a C string.
Example :
If input string was : "Hello There"
The output should be :
e - 3
h - 2
l - 2
My current code has been printing what i need,but it doesn't consider capital letters, it also keep giving me the message stack smashing detected (core dumped)
. So, it doesn't work properly and I'm not sure why :
#include <stdio.h>
#include <string.h>
int main()
{
char string[10];
int c = 0, count[26] = {0};
printf("Enter a string of size [10] or less:\n");
gets(string);
while (string[c] != '\0')
{
/**reading characters from 'a' to 'z' or 'A' to 'Z' only
and ignoring others */
if ((string[c] >= 'a' && string[c] <= 'z') || (string[c] >= 'A' && string[c] <= 'Z'))
{
if (string[c] >= 'a' && string[c] <= 'z')
{
count[string[c]-'a']++;
}
else if (string[c] >= 'A' && string[c] <= 'Z')
{
count[string[c]-'A']++;
}
}
c++;
}
for (c = 0; c < 26; c++)
{
/** Printing only those characters
whose count is at least 2 */
if (count[c] > 1)
printf("%c - %d \n",c+'a',count[c]);
}
return 0;
}
Upvotes: 1
Views: 14058
Reputation: 206627
"Hello There"
doesn't fit in a character array of size 10
. This is good example of why you should not use gets
.
Use:
fgets(string, sizeof(string), stdin);
Upvotes: 1