Reputation: 1
I'm solving the decryption problem in C language
There's a problem.
There's a process of counting the vowels in the string,
code not reading the number of vowels properly in that 'countingmeasure'
I was so curious that I debugged it,
count ++ doesn't work at'o'.
I'm really curious why this is happening
#include <stdio.h>
int main(void)
{
char original[15] = { 't','f','l','e','k','v','i','d','v','r','j','l','i','v',NULL };
printf("암호화된 문자열 : %s\n", original);
printf("원본 가능 문자열 \n");
printf("\n");
for (int j = 0; j < 26; j++)//모음이 7개일때만 출력을 어떻게 시킬까?
{
char change[14] = { 0 };
int counter=0;
char a;
for (int i = 0; i < 14; i++)
{
a = original[i] + j;
if (a > 122)
{
original[i] -= 26 ;
}
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
{
counter++;
}
printf("%c", original[i] + j);
}
printf(" %d\n",counter);
}
}
Upvotes: 0
Views: 232
Reputation: 67713
char *mystrchr(const char *str, const char lt, int ignoreCase)
{
while(*str)
{
if(ignoreCase)
if(tolower((unsigned char)*str) == tolower((unsigned char)lt)) return (char *)str;
else
if(*str == lt) return (char *)str;
str++;
}
return NULL;
}
size_t count(const char *haystack, const char *needle, int ignoreCase)
{
size_t count = 0;
while(*haystack)
{
if(mystrchr(needle, *haystack, ignoreCase)) count++;
haystack++;
}
return count;
}
int main(void)
{
char *str = "tflekvidvrjliv";
printf("%zu\n", count(str, "aeiou", 1));
}
Upvotes: 0
Reputation: 214265
a = original[i] + j;
doesn't make any sense, since a
is a char
and the result might not fit inside it. Specifically, "character value + 26" might be larger than 127. Is char signed or unsigned by default?
Furthermore, arithmetic on any symbols except '0'
to '9'
isn't well-defined and they are not guaranteed to be allocated adjacently. Also please refrain from using hard-coded "magic numbers" in source code. Instead of 122 you should use 'z'
etc.
There are several ways you can fix the program.
unsigned char a
on the existing program, if you are content with "it just works, but I don't even know what I'm doing".strchr()
search in the vowel string for a match. (Correct but naive and slow, good enough beginner solution.)const bool LOOKUP [128] = { ['A'] = true, ['a'] = true, ['E'] = true, ... };
Then check if(item[i] == LOOKUP[ item[i] ]) /* then vowel */
.Upvotes: 1