I am trying to take all the integers from the file file.txt and place them in a dynamically allocated array. However the file could also contain other characters, and these should not be put in the array.
The file contains the following:
2 -34 56 - 23423424 12example-34en+56ge-tal345
int* getIntegers(char* filename, int* pn)
{
FILE* fileInput = fopen(filename, "r");
int* temp = (int*)malloc( 100*sizeof(int));
int counter = 0;
int c= fgetc(fileInput);
while(c != EOF){
counter ++;
printf("%d;\t%d\n", counter, c);fflush(stdout);
temp[counter++] = c;
}
*pn = counter;
return (temp);
}
int main(void)
{
int n;
int* a = getIntegers("file.txt", &n);
if (a != NULL){
puts("numbers found:");
for (int i = 0;i < n; i++){
printf("%d ",a[i]);
}
free(a);
}
putchar('\n');
while(getchar()== '\n');
return (EXIT_SUCCESS);
}
when I run this the following output is returned:
Output:
1; 49
3; 49
5; 49
7; 49
9; 49
11; 49
13; 49
15; 49
17; 49
19; 49
21; 49
While the correct output should have been
found numbers:
12 -34 56 23423424 12 -34 56 345
c= fgetc(fileInput);for one time?