1

I am reading a book and I can't figure out this try it out : (it is in a non-english language so I translated it)

Write a program that ask for a number of students n, select n students (in a dynamic way), the name is 10 characters and note on 5 characters

Create a text file note.txt from the selection above and append hyphens to reach 10 characters (for the names).

Then read the file and from it (only), calculate the total. Then display the name and note of those that have a note that is not greater than 10.

You must implement 3 functions : createStudent, createFile and readFile, and not use global variables.

syntax : name must declared as char nom[10+1] (ie James, and then 5 hyphens will be added in order to get 10 characters) => james----- and note : char[5+1] (ie 15.00 or 07.50)

Tips : To convert the note from text format to float, you can use the atof function

I created the createStudent and createFile functions. they work well but I can't figure out the last part (readFile function).

My text file has this shape : Bart------ 04.50 Lisa------ 18.00 Homer----- 03.00

void readFile(int n){
FILE* file = NULL;
double temp= 0.0, average= 0.0;
double *total = (double*)malloc(n*sizeof(double));

int position = 0;
char information[5+1]="";

file = fopen("c:\\myFile.txt","r");
fseek(file,10,SEEK_SET);
while(fgetc(file) != EOF)
{
    fscanf(file,"%5s",&information);
    temp = atof(information);
    total[position]= temp;

    position++;

    fflush(stdin);
    fseek(file,11,SEEK_CUR);
}
fclose(file);
for(int compteur=0;compteur<2;compteur++)
{
    moyenne += totalNote[compteur];
}

It compiles but doesn't work and I can't figure out why :( I have the feeling that C language is such a pain in the ass compared to java or c#

Could you please give me some lights ?

Bon_chan
  • 331
  • 2
  • 5
  • 15

3 Answers3

3

It looks like your input file contains lines of the form " ". If there is always a fixed number of strings/numbers per line you can simply use fscanf (e.g. fscanf(file, "%*s %f %*s %f %*s %f", &number1, &number2, &number3);).

If, on the other hand, you can have an arbitrary number of string/number pairs per line, you should take a look at the strtok function.

MAK
  • 26,140
  • 11
  • 55
  • 86
1

You want to look into using strtok_r (or strtok if strtok_r not available). You can then convert your string into an array of token with space delimiter. Then it should be trivial to loop thur the array to convert and sum the amounts.

fseto
  • 9,898
  • 1
  • 19
  • 14
1

Use either fscanf or a combination of fgets,strtok,atol(or sscanf) to read the number.

JRK
  • 182
  • 9