-
input array with EOF
hello I have a pretty simple question in regards to EOF. My code takes an input of numbers and stores them in an array-->
Item 1 :34
Item 2 :56
Item 3 :54.543
Item 4 :-54.53
Item 5 :^D
when EOF is triggered it prints out the size of the array
size of array is 4
I would like to be able to add more to the array where it left off, for example:
Item 5 :20
Item 6 :34
Item 7 :23.3
Item 8 :^D
size of array is 7
The problem is my program terminates before I can add more data to the array , i hypothetically try to scanf at the end of main() which doesn't work, it ends my program before i can give it more instructions and im not sure why.....
Code:
#include <stdio.h>
#include <stdlib.h>
void inputData(double *arrayPtr, int *intPtr, int n);
void printData(double *arrayPtr,int n);
int main(void){
double *arrayPtr;
double x[200];
arrayPtr = x;
int n = 0;
char contin = n;
int f = 0;
inputData(arrayPtr, &n, n);
printf("\nsize of array is %d\n", n);
printf("okay you are done for now, continue?");
scanf("%c", &contin);
printf("will anything else work?");
scanf("%d", &f);
//inputData(arrayPtr,&n, n);
return 0;
}
void inputData(double *arrayPtr, int *intPtr, int n){
int i = 0;
while (printf("Item %d :", i+1) && scanf("%lf", &arrayPtr[i]) !=EOF){
i++;
}
*intPtr = i;
return i;
}
-
Code:
printf("okay you are done for now, continue?");
scanf("%c", &contin);
printf("will anything else work?");
scanf("%d", &f);
//inputData(arrayPtr,&n, n);
return 0;
}
Do you mean with //inputData() at the end or with the function enabled?
-
>it ends my program before i can give it more instructions and im not sure why.....
Because you don't tell it to continue. Wrap the parts you want to repeat in a loop. Of course, that's still not a complete solution because now you have to wrestle with the stream state (often a non-trivial exercise):
Code:
#include <stdio.h>
void inputData(double *arrayPtr, int *i, int n)
{
while (printf("Item %d :", *i+1) && scanf("%lf", &arrayPtr[*i]) !=EOF)
++*i;
/* The loop ends with stdin in an end-of-file state, which may halt further input requests */
clearerr(stdin);
}
int main(void)
{
double x[200];
char contin;
int n = 0;
do {
inputData(x, &n, n);
printf("size of array is %d\n", n);
printf("okay you are done for now, continue? ");
scanf("%c", &contin);
} while (contin == 'y');
return 0;
}
But the lesson to take away from this is if you want to repeat it, put it in a loop. :)