Saving and printing from struct in C
I am trying to analyze a text file, starting by counting and separating all words that start with a vowel and all words that start with a consonant.
Sample test file:
This is NOT a test make sure to evacuate
Current output:
Consonant: This, 0 //saving to struct
Vowel: is, 0
Consonant: NOT, 1
Vowel: a, 1
Consonant: test, 2
Consonant: make, 3
Consonant: sure, 4
Consonant: to, 5
Vowel: evacuate, 2
count: 0, is //printing from struct
count: 1, a
count: 2, evacuate
count: 0, //unable to print consonants
count: 1,
count: 2,
count: 3,
count: 4, sure
count: 5, to
As can be seen from the above output, I am able to save in the structure, but unable to print from current_word[k].non_vowel
.
Sample code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char vowel[20];
char non_vowel[20];
} word_t;
int main(int argc, char** argv) {
FILE *inp;
FILE *outp;
int i = 0;
int word_count = 0;
char c;
int char_count = 0;
int vowel_count = 0;
int consonant_count = 0;
word_t current_word[10];
char arr[100][100];
inp = fopen("string_in.txt", "r");
while ((c = fgetc(inp)) != EOF) {
if (c == ' ' || c == '\n') {
printf("\n");
arr[word_count][char_count] = '\0'; //Terminate the string
char_count = 0; //Reset the counter.
word_count++;
}
else {
arr[word_count][char_count] = c;
printf("%c",arr[word_count][char_count]);
if (char_count < 99) {
char_count++;
}
else {
char_count = 0;
}
}
}
for(i = 0; i <= word_count; i++) {
//saving to struct
if ((arr[i][0] == 'a') || (arr[i][0] == 'i') || (arr[i][0] == 'e') || (arr[i][0] == 'o')|| (arr[i][0] == 'u')) {
memcpy(¤t_word[vowel_count].vowel, arr[i], sizeof(arr[i]));
printf("\nVowel: %s, %d", current_word[vowel_count].vowel, i);
vowel_count++;
}
else {
memcpy(¤t_word[consonant_count].non_vowel, arr[i], sizeof(arr[i]));
printf("\nConsonant: %s, %d", current_word[consonant_count].non_vowel, i);
consonant_count++;
}
}
//printing from struct
for (int j = 0; j<vowel_count; j++) {
printf("count: %d, %s\n",j, current_word[j].vowel); //this prints
}
for (int k = 0; k<consonant_count; k++) {
printf("count: %d, %s\n",k, current_word[k].non_vowel); //this does not print
}
fclose(inp);
fclose(outp);
return (EXIT_SUCCESS);
}
Any suggestions on why I am unable to print from structures containing .non_vowel
?
EDIT:
For some reason, I am yet to comprehend when I change char arr[100][100];
to char arr[10][10];
, I get:
count: 0, is
count: 1, a
count: 2, evacuate
�
count: 0, This
count: 1, NOT
count: 2, test
count: 3, make
count: 4, sure
count: 5, to