1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#define MAX_LENGTH_BUFFER 50
#define MAX_LENGTH_TOKEN 50
struct clientData
{
int acctNum;
char lastName[15];
char firstName[10];
double balance;
double lastPayAmt;
};
typedef struct clientData ClientData;
int main(void)
{
static int tokenCount = 0; //number of tokens
static char *tokenArray[MAX_LENGTH_TOKEN]; // stores delimeted tokens
char *tokenPtr; //points to tokens in string
char *separators = ","; // delimeter
FILE *cfPtr; // file pointer to .csv file
char buffer[MAX_LENGTH_BUFFER + 1]; // untokenized string
int i; // counter
int ch; // single character
// create clientData with default data
ClientData client = { 0, "", "", 0.0, 0.0 };
// fopen opens the file; exits if file cannot be opened
if ((cfPtr = fopen("accounts.csv", "r")) == NULL)
{
printf("File could not be opened.\n");
}
else
{
//extracts each character from .csv file and stores it
// in the buffer array
for (i = 0; (i < (sizeof(buffer) - 1) &&
(ch = fgetc(cfPtr))); i++) {
buffer[i] = ch;
}
buffer[i] = '\0'; // append null at the end of string
tokenPtr = strtok(buffer, separators);// tokenize commas in string
//tokenizing the string
while (tokenPtr != NULL) {
tokenArray[tokenCount++] = tokenPtr;
tokenPtr = strtok(NULL, separators);
}
// assgining each token to the struct elements
client.acctNum = tokenArray[0];
strcpy(client.firstName, tokenArray[1]);
strcpy(client.lastName, tokenArray[2]);
client.balance = tokenArray[3]; // ERROR IS HERE
sscanf(tokenArray[3], "%lf", &client.balance); //FIX
//printing assigned struct variables
printf("%s \t", client.acctNum);
printf("%s \t", client.firstName);
printf("%s", client.lastName);
fclose(cfPtr); // fclose closes the file
}
_getch();
return 0;
}
|