-
simple function
Hello,
Can someone show me whats the easiest way to write a function which will scan data (numbers - double type) from "test.txt" and add it into array. Before number is written into array there must be a loop which detect if current number is in array, then skip to next number. So I dont want to have 2 same records in array.
Thanks a lot for help!
-
Here's how it should work (but you have to write the code yourself!):
1. open file
2. start a counter
3. for each line in file:
3a. scan into a char buffer using fgets
3b. use sscanf to extract the value from the string and assign to a temp value
(alternatively you can use fscanf instead of fgets + sscanf)
3c. iterate through all existing values in the array (compare with the temp value), and if it's already in there, continue on with the next line, else store that temp value to the array and increment the counter.
4. Profit!
-
I'd open the file in main(), then submit your FILE* to a function which returns the next number, and submit that to your addnumber function, which also checks for duplicates. You can make the array global or submit it to the second function. So in pseudo pseudo-code:
Code:
FILE *fp = fopen(....);
int n;
//loop
n = getnumber(fp);
addnumber(n);
//endloop
Probably you want to have a way to indicate EOF in the getnumber() func, either with a *ptr parameter or a special return value (such as a negative number if the numbers are always positive. Then you can tie that to your loop condition.