I have a completed program that works fine when the user manually types in each
ID: 3546352 • Letter: I
Question
I have a completed program that works fine when the user manually types in each value, 1 by 1, to the screen. However, I need the program to be able to read from a file, as well. When the code reads from the file, the wrong outputs show up on the screen. The details of the program can be found in the following link:
https://www.dropbox.com/s/svisecysj1tp69o/program_rules_edit.docx
The completed program can be found in this link:
https://www.dropbox.com/s/57fio3kzznx7uzh/game_edit.docx
The completed program shows my attempt at reading in the values from the text file, without any prompts shown in the sample. The text file should just contain the same data as shown in the sample input from the first document I have a link to. Can someone please give me an edited version of the program that successfully reads input from the file? Thank you so much!
Explanation / Answer
#include <stdio.h>
int games();
void play(int);
void initialize(int[][8]);
void fillboard(int[][8]);
void print(int,int[][8]);
int bombs();
void placebombs(int[][8],int);
FILE* ifp;
int main()
{
ifp = fopen("mine.txt", "r");
int i,j,n;
n=games();
for(i=1;i<=n;i++)
{
play(i);
}
return 0;
}
int games()
{
int n;
fscanf(ifp,"%d",&n);
return n;
}
int check(int i,int j,int board[][8])
{
if(board[i][j]==9)
return 1;
return 0;
}
void fillboard(int board [][8])
{
int i,j,count;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
count=0;
if(board[i][j]!=9)
{
if(i!=0&&j!=0)
count+=check(i-1,j-1,board);
if(i!=0)
count+=check(i-1,j,board);
if(i!=0&&j!=7)
count+=check(i-1,j+1,board);
if(j!=0)
count+=check(i,j-1,board);
if(j!=7)
count+=check(i,j+1,board);
if(i!=7&&j!=0)
count+=check(i+1,j-1,board);
if(i!=7)
count+=check(i+1,j,board);
if(i!=7&&j!=7)
count+=check(i+1,j+1,board);
board[i][j]=count;
}
}
}
}
void print(int game,int board[][8])
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
if(board[i][j]==9)
printf(" *");
else
printf("%2d",board[i][j]);
printf(" ");
}
}
void play(int game)
{
int board[8][8],n;
printf("Game #%d ",game);
initialize(board);
n=bombs();
placebombs(board,n);
fillboard(board);
print(game,board);
}
void initialize(int board[][8]) //initialize all loacations to 0
{
int i,j;
for(i=0;i<8;i++)
for(j=0;j<8;j++)
board[i][j]=0;
}
int bombs()
{
int n;
fscanf(ifp,"%d",&n);
printf("n is %d ",n);
return n;
}
void placebombs(int board[][8],int n)
{
int i,j;
while(n>0) //get bomb locations
{
fscanf(ifp,"%d",&i);
fscanf(ifp,"%d",&j);
if(i<0||i>7||j<0||j>7)
printf("invalid location re-enter ");
else if(board[i][j]==9)
printf("bomb already placed there re-enter ");
else
{
board[i][j]=9;
n--;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.