338,434 views
2 votes
2 votes
Write a C program that counts the number of vowels in a word. The C program reads words from an input file and then stores in an output file the word and its number of vowels. At the end it also stores the word with the most and the word with the fewest vowels. Extra bonus: Your program should handle the situation in which there are several words with the maximum and minimum number of vowels.

User Picomancer
by
2.4k points

1 Answer

21 votes
21 votes

Answer:

Step-by-step explanation:

The following code is written in C and does what the question requires. It uses the input file reads it and outputs the number of vowels to the file called output.dat

#include <ctype.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int str_count_in_chars(char *start, char *end, char *chars) {

int count = 0;

for (; start != end; count += !!strchr(chars, *(start++)));

return count;

}

void str_swap_in_chars(size_t str_len, char **str, char *chars) {

for (int front = 0, back = str_len - 1; front < back; front++) {

if (strchr(chars, (*str)[front])) {

for (; !strchr(chars, (*str)[back]); back--);

char tmp = (*str)[front];

(*str)[front] = (*str)[back];

(*str)[back--] = tmp;

}

}

}

char *file_to_str(FILE *fin) {

int buf_len = 64;

char buf[buf_len];

char *str = malloc(buf_len);

str[0] = '\0';

for (int i = 1; fgets(buf, buf_len, fin); i++) {

if (!(str = realloc(str, i * buf_len))) {

fprintf(stderr, "%s:%d realloc failed\\", __FILE__, __LINE__);

exit(1);

}

strcat(str, buf);

}

return str;

}

int main() {

char *vowels = "aeiou";

FILE *fin = fopen("input.dat", "r");

FILE *fout = fopen("output.dat", "w");

if (!fin || !fout) {

fprintf(stderr, "%s:%d fopen failed\\", __FILE__, __LINE__);

exit(1);

}

char *words = file_to_str(fin);

fclose(fin);

int words_len = strlen(words);

for (int i = 0; i < words_len;) {

if (isspace(words[i])) {

fputc(words[i++], fout);

continue;

}

int start = i;

for (; i < words_len && !isspace(words[i]); i++);

char *word = words + start;

int word_len = i - start;

int vowel_count = str_count_in_chars(word, words + i, vowels);

if (vowel_count % 2 == 0) {

str_swap_in_chars(word_len, &word, vowels);

}

fprintf(fout, "%.*s_%dvow", word_len, word, vowel_count);

}

fclose(fout);

free(words);

return 0;

}

User Anil Kumar K K
by
2.6k points