I am trying to read from a file that contains multiple lines of numbers and strings and save it to an array. However when I call upon the elements of values stored in that array, and I got incorrect results.
For example if I have a text file that has
1:Smith:John:3;43
2:Saget:Bob:5:55
3:Wayne:Bruce:7:21
I'm trying to store the objects for the first line in the array in s[0]
, second line in s[1]
, and third line in s[3]
.
Here is my struct SalesPerson
struct SalesPerson {
int salesNum; // 4-digit integer
char lastName[31]; // salesperson's last name
char firstName[31]; // salesperson's first name
int salesRate; // commission level for each salesperson
double salesAmount; //amount the salesperson committed for the week
};
Here is my main function
#include <stdio.h>
#include <stdlib.h>
#include "sales.h"
#define SIZE 1000
int main()
{
struct SalesPerson s[SIZE];
//opening the file for reading
FILE * openRead(char salesinfo[]);
{
FILE *fp;
fp = fopen("salesinfo.txt", "r");
int i;
if(fp != NULL){
//read from the file and save it to array s
for (i=0;i<SIZE;i++){
while(!feof(fp)){
fscanf(fp, "%d:%[^:]:%[^:]:%d:%lf\n" ,&s[i].salesNum, s[i].lastName, s[i].firstName, &s[i].salesRate, &s[i].salesAmount);
}
}
fclose(fp);
}
else
printf("ERROR! Cannot open the file!\n");
}
}
If I do
printf("%d\n", s[i].salesRate);
I get all the results for salesRate
.
3
5
7
However, when I try a printf
printf("%d\n", s[1].salesRate);
Instead of giving me 5
, I got an incorrect result. Can someone tell me where I am going wrong? Is my for loop condition incorrect?