I have a problem with the print output, every time it prints "12" it enters down and I don't know what is the problem, i have tried print it separately but no luck (code below)
the question
A baseball player’s batting average is calculated as the number of hits divided by the official number of at-bats. In calculating official at-bats, walks, sacrifices, and occasions when hit by the pitch are not counted. Write a program that takes an input file containing player numbers and batting records. Trips to the plate are coded in the batting record as follows: H—hit, O—out, W—walk, S—sacrifice, and P—hit by pitch. The program should output for each player the input data followed by the batting average. (Hint: Each batting record is followed by a newline character.)
Sample input file:
12 HOOOWSHHOOHPWWHO
4 OSOHHHWWOHOHOOO
7 WPOHOOHWOHHOWOO
Corresponding output:
Player 12's record: HOOOWSHHOOHPWWHO
Player 12's batting average: 0.455
Player 4's record: OSOHHHWWOHOHOOO
Player 4's batting average: 0.417
Player 7's record: WPOHOOHWOHHOWOO
Player 7's batting average: 0.364
the code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main() {
char str[1000];
int count = 0;
int count2 = 0;
char ch = 'H';
char ch2 = 'O';
double top = 0;
double bottom = 0;
double avg;
char PN[1000];
printf("Enter player's number:");
fgets(PN, sizeof(PN), stdin);
printf("Enter a record: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; ++i) { //counts H//
if (ch == str[i])
++count;
top = count;
}
for (int i = 0; str[i] != '\0'; ++i) { //counts O//
if (ch2 == str[i])
++count2;
bottom = count2;
}
avg = top / (top + bottom); // H / ( H + O ) //
printf("Player %s's record: %s", PN, str);
printf("Player %s's batting average: %.3lf", PN, avg);
return 0;
}
my code's output
input
Enter player's number:12
Enter a record: HOOOWSHHOOHPWWHO
output
Player 12
's record: HOOOWSHHOOHPWWHO
Player 12
's batting average: 0.455
should be
Player 12's record: HOOOWSHHOOHPWWHO
Player 12's batting average: 0.455
fgets()
reads and stores the trailing newline in the buffer. One way of getting rid of that is to use strcspn()
, like
PN[strcspn(PN, "\n")] = 0;