Reputation: 43
I have a .txt file called 'exampleWheel.txt' which contains 10 characters: A,M,W,O,S,E,G,L,P,H.
I am trying to store the characters inside an array so that I can reference to each character later according to its position in the array.
Here is my attempt:
#include <stdlib.h>
int main()
{
FILE * fPointer;
fPointer = fopen("exampleWheel.txt","r");
int i = 0;
char singleLine[150];
const char *array[10];
while(!feof(fPointer)){
fgets(singleLine, 150, fPointer);
array[i] = singleLine;
printf("%d\n",&array[i]);
printf("%s\n", array[i]);
i++;
}
fclose(fPointer);
printf("array[0] = %c\n", array[0]);
printf("array[1] = %c\n", array[1]);
return 0;
}
The printf statements in the while loop return the correct output but the two printf outside the while loop returns the wrong results.
i.e printf("array[0] = %c\n", array[0]) does not return the first character of the array
Please show me how to improve my code. Thank you in advance!!
Upvotes: 0
Views: 74
Reputation: 27126
array[i] = singleLine;
stores a pointer to the singleLine character array, but it will be overwritten with the next fgets call in the loop. As an alternative you could use e.g. a two-dimensional array here and simply save the first character.array
, otherwise you write over then end of the arrayYou slightly modified code could look like this then:
#include <stdlib.h>
#include <stdio.h>
#define MAX_LINES 10
int main() {
char singleLine[150];
char array[MAX_LINES][2];
FILE *fPointer;
if ((fPointer = fopen("exampleWheel.txt", "r")) == NULL) {
fprintf(stderr, "can't open file");
exit(1);
}
int i = 0;
while (i < MAX_LINES && fgets(singleLine, 150, fPointer)) {
array[i][0] = singleLine[0];
array[i][1] = '\0';
printf("%d\n", *array[i]);
printf("%s\n", array[i]);
i++;
}
fclose(fPointer);
printf("array[0] = %c\n", array[0][0]);
printf("array[1] = %c\n", array[1][0]);
return 0;
}
Upvotes: 1