#include "Header.h"
void mostraTabuleiro(int lin, int col, int **m){
int i, j, l;
char k = 65;
for (l = 1; l <= col; l++){
printf("\t%c", k);
k++;
}
printf("\n");
for (i = 1; i <= lin; i++){
printf("%d", i);
for (j = 1; j <= col; j++){
if (i == lin && j == col)
printf("\t[X]");
else
printf("\t[*] ");
}
printf("\n");
}
}
and now i want to save the mostratabuleiro in a file and i started doing this
int GuardaFicheiro(char *nome_fich){
FILE *fnovo;
char *novo_fich = "estadosTabuleiro.txt";
fnovo = fopen(novo_fich, "wt");
if (fnovo == NULL){
printf("Erro ao abrir o ficehiro de texto %s para escrita.\n", novo_fich);
return;
}
//mostraTabuleiro(6, 8, Tabuleiro, fnovo);
fclose(fnovo);
}
if i put fprintf in the function mostraTabuleiro after that it doesn't appera anything and the file is blank.
This should be corrected
fnovo = fopen(novo_fich, "wt");
into:
fnovo = fopen(novo_fich, "w");
after that use fprintf();
fprintf(fnovo, /*source char * */);
You may please note that you should ask question on S.O. in this style. You can also read this.
void mostraTabuleiro(int lin, int col, int **m, FILE *fnovo) {
int i, j, k;
for (k = 1; k <= col; k++){
fprintf(fnovo, "\t%d", k);
}
fprintf(fnovo, "\n");
for (i = 1; i <= lin; i++){
fprintf(fnovo, "%d", i);
for (j = 1; j <= col; j++){
if (i == lin && j == col)
fprintf(fnovo, "\t[X]");
else
fprintf(fnovo, "\t[*] ");
}
fprintf(fnovo, "\n");
}
}
and
void GuardaFicheiro(int lines, int columns, int **m){
FILE *fnovo;
char *novo_fich = "estadosTabuleiro.txt";
fnovo = fopen(novo_fich, "wt");
if(fnovo == NULL){
printf("error opening file %s for writing.\n", novo_fich);
return;
}
// this will write to the file
mostraTabuleiro(lines, columns, m, fnovo);
// this will write on screen : stdout
mostraTabuleiro(lines, columns, m, stdout);
fclose(fnovo);
}
and
int iniciaJogo() {
tabuleiro tab;
int i, j, m, n;
int res = 0;
int **Tabuleiro;
int cont = 0;
int iteracoes = 0;
do{
do{
printf("Dimensoes do ambiente\nLines\n");
scanf("%d", &tab.N_Linhas);
} while (tab.N_Linhas < 4 || tab.N_Linhas > 8);
do{
printf("Columns\n");
scanf("%d", &tab.N_Colunas);
} while (tab.N_Colunas < 6 || tab.N_Colunas > 10);
} while (tab.N_Linhas > tab.N_Colunas);
Tabuleiro = criaTabuleiro(tab.N_Linhas, tab.N_Colunas);
GuardaFicheiro(tab.N_Linhas, tab.N_Colunas, Tabuleiro);
//mostraTabuleiro(tab.N_Linhas, tab.N_Colunas, Tabuleiro, fnovo);
}
And, may be main like:
int main(){
iniciaJogo();
return 0;
}
I am sure the above code would work for you. But you should read little about C Programming - functions, structures, and FileIO.
There are many unused variables in your code, you may check compiling your code with gcc -Wall -Wextra yourFileName.c
Related
#include <stdio.h>
#include <stdlib.h>
#define ROWS 15
#define COLS 10
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2);
int main(void) {
int i, j;
int z, l;
int arr[ROWS][COLS];
int min;
int max;
FILE *fp;
fp = fopen("numbers2.txt", "r");
printf("------------------------------------------------------------------------------\n");
printf(" Loaded Array \n");
printf("------------------------------------------------------------------------------\n");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
fscanf(fp, "%d", &arr[i][j]);
printf("%d\t", arr[i][j]);
}
printf("\n\n");
}
do {
printf("Enter row[1-15]:\n");
scanf("%d", &z);
} while ((z > 15) || (z < 1));
do {
printf("Enter column[1-10]:\n");
scanf("%d", &l);
} while ((l > 10 || (l < 1)));
printf("------------------------------------\n");
printf("The Max of Row %d is: %d\n", z, max);
printf("The min of Column %d id: %d\n", l, min);
find_elements(arr[ROWS][COLS], i, j, &min, &max);
fclose(fp);
return 0;
}
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2) {
int k;
*p1 = mtr[a][0];
*p2 = mtr[0][b];
for (k = 1; k < COLS; k++) {
if (*p1 <= mtr[a][k])
*p1 = mtr[a][k];
}
for (k = 1; k < ROWS; k++) {
if (*p2 >= mtr[k][b])
*p2 = mtr[k][b];
}
}
When I compile this program the following message appears:
[Warning] passing argument 1 of 'find_elements'
makes pointer from integer without a cast
[Note] expected 'int (*)[10]' but argument is of type 'int'
I am programming for about 3 months in C without a previous experience on programming before, so I can't understand what I am doing wrong. I need some help.
Thank you
As the comments point out, in this line:
find_elements(arr[ROWS][COLS],i,j,&min,&max);
the first argument of the function call is a single int, and in fact an int that doesn't even exist, which invokes undefined behavior.
What you need to do is, pass the entire array to the function, like this:
find_elements(arr,i,j,&min,&max);
// ^^^ just the array name
There are at least 3 problems in your code:
you should just pass arr as the first argument to find_elements,
you should move the function call before the printf.
you should pass z and l instead of i and j.
why are row 0 and column 0 excluded from the search?
Here is a modified version:
#include <stdio.h>
#define ROWS 15
#define COLS 10
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2);
int main(void) {
int i, j, z, l;
int arr[ROWS][COLS];
int min, max;
int c;
FILE *fp;
fp = fopen("numbers2.txt", "r");
if (fp == NULL) {
printf("cannot open numbers2.txt\n");
return 1;
}
printf("------------------------------------------------------------------------------\n");
printf(" Loaded Array \n");
printf("------------------------------------------------------------------------------\n");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (fscanf(fp, "%d", &arr[i][j]) != 1) {
printf("invalid data\n");
return 1;
}
printf("%d\t", arr[i][j]);
}
printf("\n\n");
}
fclose(fp);
do {
printf("Enter row[1-%d]:\n", ROWS);
if (scanf("%d", &z) != 1) {
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF) {
printf("end of file\n");
return 1;
}
printf("invalid entry\n");
continue;
}
} while (z > ROWS || z < 1);
do {
printf("Enter column[1-%d]:\n", COLS);
if (scanf("%d", &l) != 1) {
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF) {
printf("end of file\n");
return 1;
}
printf("invalid entry\n");
continue;
}
} while (l > COLS || l < 1);
find_elements(arr, z, l, &min, &max);
printf("------------------------------------\n");
printf("The Max of Row %d is: %d\n", z, max);
printf("The min of Column %d id: %d\n", l, min);
return 0;
}
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2) {
int k;
*p1 = mtr[a][0];
*p2 = mtr[0][b];
for (k = 1; k < COLS; k++) {
if (*p1 < mtr[a][k])
*p1 = mtr[a][k];
}
for (k = 1; k < ROWS; k++) {
if (*p2 > mtr[k][b])
*p2 = mtr[k][b];
}
}
int main(){
int word, r=3, i, j;
FILE *fp1 = fopen("key.txt","r");
int **arr = (int **)malloc(sizeof(int *) * r);
for(i = 0;i<r;i++)
arr[i] = (int *)malloc(sizeof(int)*r);
int a = 0, b = 0;
while (!feof(fp1)) {
fscanf(fp1,"%d",&word);
if (b == r){
a++;
b=0;
continue;
}
arr[a][b++] = word;
}
for (i = 0; i < r; i++)
for (j = 0; j < r; j++)
printf("%d \n", arr[i][j]);
fclose(fp1);
}
And this is my key.txt.
0 -1 0
-1 2 -1
0 -1 0
I want to store key.txt in a dynamic 2d array but it did not work. All the time a part of it is missing. Which part is wrong?
You should use fscanf in while, not feof
You should delete continue.
The follow code could work:
#include <stdio.h>
#include <stdlib.h>
int main(){
int word, r=3, i, j;
FILE *fp1 = fopen("key.txt","r");
int **arr = (int **)malloc(sizeof(int *) * r);
for(i = 0;i<r;i++)
arr[i] = (int *)malloc(sizeof(int)*r);
int a = 0, b = 0;
while (fscanf(fp1,"%d",&word) == 1) {
if (b == r) {
a++;
b=0;
}
arr[a][b++] = word;
}
for (i = 0; i < r; i++) {
for (j = 0; j < r; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
fclose(fp1);
return 0;
}
so I'm having trouble solving a problem for my IT exam.
I solved it and it partially worked but I could find a solution only using a BFS and I'm sure this doesn't require graph traversal algorithms since we haven't done them yet but I can't find any other solution. Could someone give me a hint.I'll post the BFS code down under just to how that I've actually solved this but not how I think it should've been solved.
#include <stdio.h>
#include <stdlib.h>
char file[20][20];
int v[20], ns, n, comp, c[20];
int prim;
int ultim;
FILE *f;
int nr = 0, nl, nc;
void matrix() {
int i, j;
char c, n;
fscanf(f, "%d %d \n", &nl, &nc);
for (i = 1; i <= nl; i++) {
for (j = 1; j <= nc; j++) {
c = getc(f);
file[i][j] = c;
}
n = getc(f);
}
}
// citirea grafului din fisier text si construirea matricei de adiacenta
// afisarea pe ecran a matricei de adiacenta
void afisare() {
int i, j;
printf("Matricea : \n");
for (i = 1; i <= nl; i++)
{
for (j = 1; j <= nc; j++)
printf("%c", file[i][j]);
printf("\n");
}
}
// returnează primului nod nevizitat
int exista_nod_nevizitat(int v[20], int n) {
int i, j;
for (i = 1; i <= nl; i++)
if (v[i] == 0)
return i; // primul nod nevizitat
return 0; // nu mai exista noduri nevizitate
}
// parcurgerea în latime a unei componente conexe, plecând din nodul de start ns
void parcurgere_latime(char file[20][20], int nl, int ns) {
int i, j;
comp++;
v[ns] = 1;
prim = ultim = 1;
c[ultim] = ns;
while (prim <= ultim) {
for (i = 1; i <= nl; i++)
if (file[c[prim]][i] == 'L')
if (v[i] == 0)
{
ultim++;
c[ultim] = i;
v[i] = 1;
}
prim++;
}
}
// functia principala main()
int main() {
int set, nr;
f = fopen("in1.txt", "r");
fscanf(f, "%d \n", &set);
while (set != 0) {
matrix();
afisare();
while (exista_nod_nevizitat(v, n) != 0) {
ns = exista_nod_nevizitat(v, n);
parcurgere_latime(file, n, ns); // parcurg o alta componenta conexa
}
printf("Graful este alcătuit din ");
printf("%d", comp);
printf("componente conexe \n");
set--;
}
return 0;
}
Found this solution which seems to be easier and faster
int countIslands(char a[100][100])
{
int count = 0;
for ( i=0; i<nl; i++)
{
for (j=0; j<nc; j++)
{
if (a[i][j] == 'L')
{
if ((i == 0 || a[i-1][j] == '.') &&
(j == 0 || a[i][j-1] == '.'))
count++;
}
}
}
return count;
}
I'll type out a pretty basic solution which comes to mind. Note that it is not certainly not optimal and is a bit of a brute-force approach.
Basically, what I'm thinking of is traversing the matrix element by element, and every time you find an L (beginning of the island), find its borders by going from neighbour to neighbour and marking it down with the number of the current island until there's no more neighbours for the elements of the island, then continue traversing the matrix, repeating the same steps every time you find an L that has not been marked.
I need help here! I'm trying to code a console-based C program which solves several systems of equations.
Exercise:
The program receives an entry file (input and output file names typed in by the user), containing n, m, and a bunch of numbers which will fill in a matrix. This matrix is an extended matrix which has n rows and n+m columns (where m is the number of systems to solve). First "submatrix" nxn must be reduced using Gauss Elimination method with pivoting.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int gauss_pivot (double **a, int n, int m, double tol);
void resol (double **a, int n, int m);
int main(void) {
double **ampliada;
int n, m;
int i, j;
FILE *entrada, *sortida;
char nomE[31], nomS[31];
printf("Noms dels fitxers d'entrada i sortida\n");
scanf("%s %s", nomE, nomS);
entrada = fopen(nomE, "r");
sortida = fopen(nomS, "w");
if (entrada == NULL || sortida == NULL){
if (entrada == NULL){
printf("Error en el fitxer d'entrada\n");
exit(1);
}
else{
printf("Error en el fitxer de sortida\n");
exit(1);
}
}
fscanf(entrada, "%d", &n);
fscanf(entrada, "%d", &m);
ampliada = (double**)malloc(n*sizeof(double*));
if (ampliada == NULL) {
printf("Memòria insuficient\n");
exit(1);
}
for (i=0; i<n; i++){
ampliada[i] = (double*)malloc(m*sizeof(double));
if (ampliada[i] == NULL){
printf("Memòria insuficient\n");
exit(1);
}
}
for (i=0; i<n; i++){
for (j=0; j<=m; j++){
fscanf(entrada, "%le", &liada[i][j]);
}
}
gauss_pivot(ampliada, n, m, 10^(-16));
resol(ampliada, n, m);
return 0;
}
int gauss_pivot (double **a, int n, int m, double tol){
float q;
double pivot, aux;
int r;
for (int j = 0; j < n; j++){
pivot = 0;
for (r = j; r < n; r++){
if (fabs(a[r][j]) > pivot){
pivot = a[r][j];
}
}
if (pivot != a[j][j]){
for (int s = 0; s < (n+m); s++){
aux = a[r][s];
a[r][s] = a[j][s];
a[j][s] = aux;
}
}
for (int i = 0; i < n; i++){
if(i > j){
q = a[i][j]/a[j][j];
for (int k = 0; k < (n+m); k++){
a[i][k] = a[i][k] - q*a[j][k];
}
}
}
}
return 0;
}
void resol (double **a, int n, int m){
double resultats[n], suma;
for (int s = 1; s <= m; s++){
printf("Solució al sistema %d:\n", s);
resultats[n]=a[n][n+1]/a[n][n];
for(int i = n-1; i >= 1; i--){
suma=0;
for(int j=i+1; j<=n; j++){
suma=suma+a[i][j]*resultats[j];
}
resultats[i]=(a[i][n+1]-suma)/a[i][i];
}
for (int r = 1; r <= n; r++){
printf("X_%d = %f", r, resultats[r]);
}
}
}
It crashes on the following lines (sometimes one, somtimes the other):
aux = a[r][s];
a[r][s] = a[j][s];
a[j][s] = aux;
And I get the following error message:
Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
What am I doing wrong?
I am trying to store the coordinates (x, y) in a text file, where x denotes the row number and y the column. I will then use this information to change the element of the array to 1, and the others will remain at 0. I want to do this multiple times to the same .txt file. I'm trying to simulate the famous Game of Life. The trouble is that is only successfully reads from the file once so the array cannot update, and so the array just prints off the same stuff as before.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 30
#define COLS 20
#define ITERATIONS 6
int fillBoard(int b[ROWS][COLS]);
int newRound(FILE *i, int b[ROWS][COLS]);
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]);
int cellBirth(FILE *p, int b[ROWS][COLS]);
int main(void) {
int board[ROWS][COLS];
char fileName[] = "#life 1.06";
int i, j;
int x, y;
int round = 0;
FILE *fp, *ifp;
char fileFormat[11];
int p, o;
fp = fopen("life.txt", "r");
ifp = fopen("life2.txt", "r");
if (fp == NULL) {
printf("Error\n");
exit(1);
}
if (ifp == NULL) {
exit(1);
}
fillBoard(board);
fgets(fileFormat, 11, fp); // read input from first line
if (strcmp(fileName, fileFormat) == 0) {
while (fscanf(fp, "%d %d", &x, &y) == 2) {
board[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
} else {
printf("Wrong file");
}
// print game with the starter cells
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", board[i][j]);
}
}
newRound(ifp, board);
fclose(fp);
fclose(ifp);
return(0);
}
int newRound(FILE *ij, int b[ROWS][COLS]) {
int round = 0;
int x, y;
int i, j;
while (round < ITERATIONS) {
printf("\n");
cellAliveOrDead(ij, b);
cellBirth(ij, b);
fillBoard(b);
while (fscanf(ij, "%d %d", &x, &y) == 2) {
b[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
round++;
// print game round 2
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", b[i][j]);
}
}
}
}
int fillBoard(int b[ROWS][COLS]) {
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
b[i][j] = 0;
}
}
}
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if(b[i][j] == 1) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if(count == 2 || count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
int cellBirth(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if (b[i][j] == 0) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if (count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
The simplest answer would be to use 2 files.
Write into a FILE* A. Then close it and read it as FILE* B, and write into a FILE* A. Repeat.
The other method would be to use fseek. This is quite risky as the chances of you rewriting on top of essential information is quite possible. But follow this answer, and you should be fine.
Also see this if you are curious about how fseek works.