Reputation: 31
I want to read a .dat file whose first line consists of a float and all consecutive lines are "int * int" or "int / int" and print or return whether the float is a result each division or multiplication. I am very unpleased with the results that I am getting. My experience is limited to only a couple of hours doing C. Therefore I have no idea what is missing for the program to do what the code is looking like it would do.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int countlines(FILE* f){
int nLines = -1;
char xLine[10];
while(fgets(xLine,10,f)!=NULL){
nLines+=1;
}
return nLines;
}
int main(){
FILE * fPointer = fopen("test.dat", "r");
float dpFloat;
char oprnd[10];
int frstInt;
int scndInt;
//get float from first line
fscanf(fPointer, "%f", &dpFloat);
//count amount of lines below float
int amtLines = countlines(fPointer);
//loop through the other lines and get
int i;
for (i = 0; i < amtLines; i++){
fscanf(fPointer, "%d %s %d", &frstInt, oprnd, &scndInt);
//checking what has been read
printf("%d. %d %s %d\n", i, frstInt, oprnd, scndInt);
//print 1 if firstline float is quot/prod of consecutive line/s
//else 0
if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);
}
fclose(fPointer);
return 0;
}
Upvotes: 3
Views: 146
Reputation: 206567
Problem 1: strcmp
returns 0
when its arguments are equal, not 1.
Problem 2: frstInt/scndInt
will truncate the result. Fix it by adding 1.0*
to the expression.
The lines
if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);
need to be
if (strcmp(oprnd,"*") == 0) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") == 0) printf("%i\n", (1.0*frstInt/scndInt)==dpFloat);
// ^^^ ^^^
Please be aware of the pitfalls of comparing floating point numbers. It's best to compare them within a tolerance. See Comparing floating point numbers in C for some helpful tips.
Upvotes: 2