#include <stdio.h>
#include <stdlib.h>
#define MAX 21
#define MAX_ELEM 8
#define SCORE 12
#define NUM_SKATER 4
#define BASE 3.1
typedef struct{
char name[MAX];
int elements;
float baseval[MAX_ELEM];
int score[MAX_ELEM][SCORE];
float total_base;
float tech_score;
float total_score;
}SKATER;
int getData(SKATER skater[NUM_SKATER]);
int main (void)
{
// Global Declarations
SKATER skater[NUM_SKATER];
// Function calls
getData(skater);
return 0;
}
/********************************* getData ************************************
Pre:
Post:
*/
int getData(SKATER skater[NUM_SKATER])
{
// LOcal Declarations
FILE* fpIn;
int i = 0;
int k;
int j;
char buffer[256];
// Statements
if((fpIn = fopen("lab6data.txt","r"))==NULL)
{
printf("File opening error");
system("PAUSE");
exit(100);
}
while(i < NUM_SKATER && fgets(buffer, sizeof(buffer) - 1, fpIn))
{
sscanf(buffer,"%19[^0123456789]", &skater[i].name);
for(k = 0; k < MAX_ELEM; k++)
{puts(buffer);
if(fgets(buffer, sizeof(buffer)-1, fpIn) != NULL)
{
sscanf(buffer,"%d %f", &skater[i].elements, &skater[i].baseval[k]);
for(j = 0; j < SCORE; j++)
{
sscanf(buffer,"%d", &skater[i].score[k][j]);
}
}
}
i++;
}
system("PAUSE");
fclose(fpIn);
return i;
}
I am having some trouble with reading the data from the file, so when I add a printf to the sscanf of the score and found out that it was actually print out the element numbers but not the score. I am confused about how this happen.
Can anyone suggest away to fix this or explain to me what happen to the score?
lets say that the sample data was
1 13.0 1 2 3 0 0 0 2 1 0 3
with the first number being the elements number, the second number is the base number and the rest is scores
now that i wanted to print out score it would print out
1 1 1 1 1 1 1 1 1 1
instead of
1 2 3 0 0 0 2 1 0 3
The problem you have is that you are assuming that
sscanfdoes some magic, namely that it remembers where it was inbufferafter the last time it was called.sscanfdoes no such magic, it will being processing at the start of the string you give it, no matter how many times you’ve called it before with that same string.So the nested
is always reading the very first
intinbuffer, i.e.1in your sample. There is no “overwriting” going on, you’re just reading the same thing over and over again.To make this work, you’ll need to keep track of where you should restart parsing yourself. This can be done by using the
%nformat specifier, and a “cursor”char *into your buffer for example.Here’s a sample of how you use that:
Try running this code with different parameters: