I am trying to get vowels and consonants separately and save them into "vowels.txt" and "consonant.txt" from a string which is located at a file. But consonants are found correctly but vowels are not. Please take a look at my code snippet and help to figure out how can I solve this problem.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int vowelIndex = 0;
int consIndex = 0;
int isVowel(char chr) {
switch(chr) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 1;
default:
return 0;
}
}
char *readFile() {
FILE* fp = fopen("character.txt","r");
char str1[20];
char* buffer = (char*)malloc(sizeof(char)*50);
// fscanf(fp,"%s",str1);
for (int i = 0; i < 6;i++) {
fscanf(fp,"%s",str1);
strcat(buffer,str1);
strcat(buffer," ");
}
fclose(fp);
return buffer;
}
void writeFile(char* fname, char* content) {
FILE* fp = fopen(fname,"w"); // accessing the file in write mode
fputs(content,fp);
fclose(fp);
}
int main(void) {
char *buff = readFile();
char *vowels = (char*)malloc(sizeof(char)*18);
char *cons = (char*)malloc(sizeof(char)*30);
for (int i = 0; i < strlen(buff); i++) {
if (isVowel(buff[i])) {
printf("buffer inspect : %c\n",buff[i]);
vowels[vowelIndex] = buff[i];
vowelIndex++;
} else {
cons[consIndex] = buff[i];
consIndex++;
}
}
printf("\nVowerls : %s\n",vowels);
printf("\nCons : %s\n",cons);
writeFile("vowels.txt",vowels); // writing to the file
writeFile("consonant.txt",cons); // writing to the file:
return 0;
}
Please help me to find this.
Your logic for finding if character is vowel or character is correct but there is problem with file and null character handling.
Change function readFile as below:
char *readFile() {
FILE* fp = fopen("character.txt","r");
char str1[20];
char* buffer = (char*)malloc(sizeof(char)*50);
int i;
fgets(buffer,50,fp);
/* fscanf(fp,"%s",buffer);
for ( i = 0; i < 6;i++) {
fscanf(fp,"%s",str1);
strcat(buffer,str1);
strcat(buffer," ");
}
*/ fclose(fp);
return buffer;
}
And in main, after for loop, add null character at the end of vowels and cons string as below.
int main(void) {
char *buff = readFile();
char *vowels = (char*)malloc(sizeof(char)*18);
char *cons = (char*)malloc(sizeof(char)*30);
int i;
printf("strlen = %d\n",strlen(buff));
for (i = 0; i < strlen(buff); i++) {
if (isVowel(buff[i])) {
printf("buffer inspect : %c\n",buff[i]);
vowels[vowelIndex] = buff[i];
vowelIndex++;
} else {
cons[consIndex] = buff[i];
consIndex++;
}
}
vowels[vowelIndex] = '\0';
cons[consIndex] = '\0';
printf("\nVowels : %s\n",vowels);
printf("\nCons : %s\n",cons);
writeFile("vowels.txt",vowels); // writing to the file
writeFile("consonant.txt",cons); // writing to the file:
return 0;
}