I’m having issues with storing the characters of a person’s initial into a char array (string) from a file that is structured as follows:
AB Albert Bumble
FG Fred Goofoff
GF Gary Flintstone
DD Donald Duck
char finitlett[MAX] will store all the first letter of the initials, A F G D.
char sinitlett[MAX] will store all the first letter of the initials, B G F D.
The problem is when I print strlen(finitlett) the number is greater than the number of entries in the file.
This is the code I created to retrieve the entries and put them into the array as follows:
void readf(char finitlett[], char sinitlett[], char name[][80])
{
char fileName[20] = "text.dat";
FILE*inFile = NULL;
inFile = fopen(fileName, "r");
if (inFile == NULL)
{
printf("Error in opening the file %s\n", fileName);
exit(0);
}
int i = 0;
while(fscanf(inFile, "%c%c%80[^\n]\n", &finitlett[i], &sinitlett[i], &name[i]) != EOF){
printf("Initials : %c%c | Name : %s\n", finitlett[i], sinitlett[i], name[i]);
i++;
}
fclose(inFile);
printf("Number of entries: %d\n", i);
printf("Length of array: %d\n", strlen(finitlett));
printf("Length of array: %d\n", strlen(sinitlett));
}
Make sure you are initializing your arrays with ‘\0’ characters. Strlen works by finding the first ‘\0’ character and if your array isn’t fully populated with these to begin with strlen could be counting “garbage data” left in the char array as part of your string.