A few issues:
- The
for
loop for counting spaces is incorrect.
- We should have a separate function to count vowels.
- Never use
gets
(use fgets
instead).
- The code did not preserve the original buffer as the code comments suggested.
I need to count which words in the text contain 4 different vowels.
So, we can only count unique vowels in a word (e.g.):
fleece
has only 1 unique vowel and not 3.
great
has 2 vowels
greet
has 1 vowel
incombustible
has 4 [unique] vowels and not 5.
It's not totally clear, but I interpret this to mean that a candidate word has at least 4 unique vowels (i.e. it could have 5)
I had to refactor quite a bit of the code. It is annotated:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
#define MAX 100
// vcount -- count _unique_ vowels
// RETURNS: number of _unique_ vowels
int
vcount(const char *str)
{
const char *vowels = "aeiou";
int vfreq[5] = { 0 };
int vsum = 0;
// loop through all chars in string
for (int chr = *str++; chr != 0; chr = *str++) {
// get lower case
chr = tolower((unsigned char) chr);
// is it a vowel?
const char *vptr = strchr(vowels,chr);
if (vptr == NULL)
continue;
// get index into frequency table
ptrdiff_t vidx = vptr - vowels;
// have we seen it before?
if (vfreq[vidx])
continue;
// mark as already seen
vfreq[vidx] = 1;
// count new unique vowel
++vsum;
}
return vsum;
}
int
main(void)
{
char phrase[MAX];
char temp[MAX];
const char *delim = " \t\v";
printf("Ingrese un texto corto: ");
// Short text with spaces
// NOTE/BUG: _never_ use gets
#if 0
gets(phrase);
#else
fgets(phrase,sizeof(phrase),stdin);
#endif
printf("\n");
// NOTE/BUG: loop condition is incorrect
#if 0
for (i = 0; x < phrase[x] != '\0'; ++x) {
if (phrase[x] == ' ' || phrase[x] == '\t' || phrase[x] == '\v') {
// Detect space.
}
}
#else
int space_count = 0;
for (int i = 0; phrase[i] != '\0'; ++i) {
switch (phrase[i]) {
case ' ':
case '\t':
case '\v':
++space_count;
break;
}
}
printf("Spaces: %d\n",space_count);
#endif
// I need to keep all the words separate.
#if 0
char *ptr = strtok(phrase, delim);
#else
strcpy(temp,phrase);
char *ptr = strtok(temp, delim);
#endif
while (ptr != NULL) {
#if 0
printf("%s\n", ptr);
#else
printf("%s -- has enough vowels: %s\n",
ptr,(vcount(ptr) >= 4) ? "Yes" : "No");
#endif
ptr = strtok(NULL, delim);
}
return 0;
}
In the above code, I used cpp
conditionals to denote old vs new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
For the input:
Ana come en el refrigerador.
Here is the program output:
Ingrese un texto corto:
Spaces: 4
Ana -- has enough vowels: No
come -- has enough vowels: No
en -- has enough vowels: No
el -- has enough vowels: No
refrigerador. -- has enough vowels: Yes