未正确找到元音显示异常结果

Vowels are not found correctly showing unusuall results

我正在尝试分别获取元音和辅音并将它们保存到"vowels.txt"和"consonant.txt" 来自位于文件中的字符串。但是正确找到了辅音,但没有找到元音。请查看我的代码片段并帮助找出如何解决此问题。

#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;
}

请帮我找到这个。

您判断字符是元音还是字符的逻辑是正确的,但是文件和空字符处理有问题。

更改函数 readFile 如下:

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;

}

然后在main中,for循环后,在元音和cons字符串的末尾添加空字符,如下所示。

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] = '[=11=]';
    cons[consIndex] = '[=11=]';

    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;
}