Write a program that 1allows you to write stats of a monster
Write a program that 1.allows you to write stats of a monster and save it to a file. (for cs132, in binary, cs131 in text format) (Things like Name, Hit Points, Minimum damage and Maximum damage.) 2.Allows you to open the file and read the stats of the monster. (Print what was read onto the screen.) Allow the program to load the stats of two monsters and let them battle it out. Homework helps: 1. Create monster stats 2. Ask the user if creating or loading 3a. If loading 1.open file for reading 2.read stats in from file (fscanf) 3.print stats to screen 3b. If creating 1.open file for writing 2.write stats to file (fprintf) - make sure to leave spaces or returns between variables, so all values do not get smooshed together
Solution
Code:
#include <stdio.h>
 #include <io.h>
 #include <stdlib.h>
 #include<conio.h>
 #include<iostream>
 int main(void)
 {
 FILE *fp;
 char name[80], choice, ch=\'y\';
 int hitPoints, minDamage, maxDamage;
 printf(\"Enter your choice (1 or 2) - \ \");
 printf(\"1. Display monster stas.\ \");
 printf(\"2. Create monster stas.\ \");
 printf(\"Your choice please - \");
 scanf(\"%c\", &choice);
if( choice == \'1\' ){ // reading stats from file and displaying in std out.
 if((fp=fopen(\"stat.txt\", \"r\")) == NULL) {
 printf(\"Cannot open file.\ \");
 exit(1);
 }else{  
 printf(\"Name\\t HitPoint\\t minDamage \\t maxDamage\ \");
 printf(\"-------------------------------------------------------\ \");
  while(fscanf(fp, \"%s %d %d %d\", name, &hitPoints, &minDamage, &maxDamage) == 4){
 fprintf(stdout, \"%s\\t %d \\t %d \\t %d \ \", name, hitPoints, minDamage, maxDamage);
 }                  
 fclose(fp);
 }
 }else if( choice == \'2\' ){ // reading from standard input and storing in file
 if((fp=fopen(\"stat.txt\", \"w\")) == NULL) {
 printf(\"Cannot open file.\ \");
 exit(1);
 }else{
 printf(\"\ Please enter monster stat data.\ \");
 while(ch == \'Y\' || ch == \'y\'){
 printf(\"\ Name - \");
 fscanf(stdin, \"%s\", name);
 printf(\"\ Hit points - \");
 fscanf(stdin, \"%d\", &hitPoints);
 printf(\"\ Min Damage - \");
 fscanf(stdin, \"%d\", &minDamage);
 printf(\"\ Max Damage - \");
 fscanf(stdin, \"%d\", &maxDamage);
 fprintf(fp, \"%s %d %d %d\ \", name, hitPoints, minDamage, maxDamage);
 printf(\"\ \ Do you want to enter more record (y/n)-\");
 scanf(\" %c\", &ch);
 }
 fclose(fp);
 }
 }
 system(\"pause\");
 return 0;
 }
Output:
Enter your choice (1 or 2) -
 1. Display monster stas.
 2. Create monster stas.
 Your choice please - 1
 Name HitPoint minDamage maxDamage
 -------------------------------------------------------
 dri 20 12 15
 dha 25 12 22
 Press any key to continue . . .
stat.txt
dri 20 12 15
 dha 25 12 22


