I really don't know what's wrong - c

This software may calulate the min e max temperature of some cities entered by keybord, but I've some problems with the scanf or the printf, because it shows the ram register value instood the effictive data. I don't know why my simple c script don't work any idea? (may the problems is on the scanf %g of the &rilevazioni[i].temp)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char nome [30] ;
double temp;
}meteo;
int main(int argc, char* argv[]) {
meteo rilevazioni[20];
meteo min, max;
double media = 0;
int i = 0;
int app = 0;
int n;
printf("quante citta' vuole inserire? (max 20 citta')\n");
scanf("%d",&n);
printf("\n Inseriamo le rilevazioni");
for (i = 0; i < n; i++)
{
printf("\n Inserisci il nome : ");
scanf("%s", rilevazioni[i].nome);
printf("\n Inserisci la temperatura : ");
fflush(stdin);
scanf("%g", &rilevazioni[i].temp);
if (i == 0)
min = max = rilevazioni[i];
else
if (min.temp > rilevazioni[i].temp)
min = rilevazioni[i];
else if (max.temp < rilevazioni[i].temp)
max = rilevazioni[i];
media += rilevazioni[i].temp;
}
fflush(stdin);
media = media / n;
printf("\n La citta' con temperatura minima e': %s con una temperatura di: %g gradi ", min.nome, min.temp);
printf("\n La citta' con temperatura massima e': %s con una temperatura di: %g gradi ", max.nome, max.temp);
printf("\n Le citta' con temperatura maggiore rispetto alla media (%f) sono:", media);
for (i = 0; i < n; i++)
{
if (rilevazioni[i].temp > media)
printf("\n La citta' : %s ha una temperatura di: %g gradi ", rilevazioni[i].nome, rilevazioni[i].temp);
}
}

Compiling your code will GCC and warnings on (gcc temp.c -Wall), it says:
test.c:25:17: warning: format ‘%g’ expects argument of type ‘float *’, but argument 2 has type ‘double *’
And indeed, %g expects a float*, if you want to read a double use %lg.
This is confusing, because there is no such distinction when calling printf(), but that is because when calling printf all arguments suffer default promotion, and all float values are promoted to double. But with scanf() you are passing pointers to values, so that promotion does not apply and you must be extra careful.

This code can help you ,I compile my code with GCC
I found the index of min & max temperature (i_min & i_max) and I print the two cities which they have max_temperature & min_temperature like this
#include <stdio.h>
#include <stdlib.h>
typedef struct meteo{
char nome [30] ;
double temp;
}meteo;
int main(int argc, char* argv[]) {
double media = 0;
int i = 0, app = 0,n=0;
do
{
printf("quante citta' vuole inserire?\n");
scanf("%d",&n);
}while(n<1||n>20);
meteo rilevazioni[n];
printf("\n Inseriamo le rilevazioni");
double min, max;
int i_min=0,i_max=0,k=0;
for (i = 0; i < n; i++)
{
printf("\n Inserisci il nome : ");
scanf(" %s", rilevazioni[i].nome);
printf("\n Inserisci la temperatura : ");
scanf("%lf", &rilevazioni[i].temp);
if (i == 0)
{
min = max = rilevazioni[0].temp;
}
else
{k++;
if (rilevazioni[k].temp<min)
{
i_min=k;
min = rilevazioni[k].temp;
}
if (rilevazioni[k].temp > max)
{
i_max=k;
max = rilevazioni[k].temp;
}
}
}
printf("\n La citta' con temperatura minima e': %s con una temperatura : %lf gradi ", rilevazioni[i_min].nome, rilevazioni[i_min].temp);
printf("\n La citta' con temperatura massima e': %s con una temperatura : %lf gradi ", rilevazioni[i_max].nome, rilevazioni[i_max].temp);
}

Related

How to use correctly tridimensional arrays to save and print strings?

I have to save three different strings in n number of 2D arrays, for that reason I created a 3D array named datosCliente[size][4][size]. After that I have to print their content. But when I'm printing the strings in the first and second string the first character disappear, and the third string isn't printed.
The first string is the name of a country.
The second is the date of departure.
The last is the date of return.
This is the code:
#include <stdio.h>
#include <stdlib.h>
const int size = 100;
void ingresoDatos(char [size][4][size], int*);
void imprimirDatos(char [size][4][size], int*);
int main(void) {
char datosCliente[size][4][size];
int cant;
FILE *document;
document = fopen("data.txt", "a");
if(document == NULL) {
printf("Error al abrir el archivo.\n");
}else {
ingresoDatos(datosCliente, &cant);
imprimirDatos(datosCliente, &cant);
}
fclose(document);
return 0;
}
void ingresoDatos(char datos[size][4][size], int *cant) {
int tam = 0;
system("clear");
printf("Ingreso de datos\n");
do {
printf("Ingrese el número de clientes: ");
scanf("%d", &tam);
}while(tam >= 100 || tam <= 0);
*cant = tam;
for(int i = 1; i <= tam; i++) {
system("clear");
printf("Ingrese el destino: ");
fgets(&datos[i][0][0], 20, stdin);
getchar();
printf("Ingrese la fecha de salida: ");
fgets(&datos[i][1][0], 30, stdin);
getchar();
printf("Ingrese la fecha regreso: ");
fgets(&datos[i][2][0], 30, stdin);
getchar();
}
}
void imprimirDatos(char datos[size][4][size], int *cant) {
system("clear");
for(int i = 1; i <= *cant; i++) {
printf("Cliente %d:\n", i+1);
printf("Destino: %s", &datos[i][0][100]);
printf("Fecha de salida: %s", &datos[i][1][100]);
printf("Fecha de regreso: %s", &datos[i][2][100]);
printf("\n");
}
}
I enter this data:
tam: 1
Destino (to): China
Fecha de salida (depart in): 23 de septiembre de 2022
Fecha de regreso (return in): 24 de noviembre de 2022
And this is the output:
Cliente 1:
Destino: hina
Fecha de salida: 3 de septiembre de 2022
Fecha de regreso:
I had forgotten mention but I'm using Replit to do the code.
scanf("%d", &tam); doesn't consume a newline character even if it is entered. (c - fgets doesn't work after scanf - Stack Overflow) In my opinion, you shouldn't mix scanf() and fgets(). You can use fgets() to read a line and sscanf() to parse the line.
fgets() consumes a newline character (if it is entered). Calling getchar(); after that will drop the first character of the next line.
Considering these points, the function ingresoDatos should be:
void ingresoDatos(char datos[size][4][size], int *cant) {
int tam = 0;
system("clear");
printf("Ingreso de datos\n");
do {
char buffer[100];
printf("Ingrese el número de clientes: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &tam);
}while(tam >= 100 || tam <= 0);
*cant = tam;
for(int i = 1; i <= tam; i++) {
system("clear");
printf("Ingrese el destino: ");
fgets(&datos[i][0][0], 20, stdin);
printf("Ingrese la fecha de salida: ");
fgets(&datos[i][1][0], 30, stdin);
printf("Ingrese la fecha regreso: ");
fgets(&datos[i][2][0], 30, stdin);
}
}

Cannot figure out how to check a value in C code

Hello I'm fairly new to programming so here's my problem, I have multiple arrays of the size x,
I want to add b values to my array, what I did is x + b then ask the user to type his value then call a function that looks if the value is already in the array, if it is, I ask the user to type it again, but the problem is that the search function returns random numbers. heres my code (the fRecherche2 works fine outside of fAjouter):
int fRecherche2 (int ref[],int n,int nref)
{
int i;
for (i=0;i<n;i++)
if (ref[i]==nref)
return i;
return -1;
}
int fAjouter(int ref[],int qt[],float prix[],int sds[],int n)
{
int i,prods,nb,code,nref;
printf("How many products would you like to add:");
scanf("%d",& prods);
fVerifVal(prods);
n=NbArticle();
nb=n+prods;
for(i=n;i<nb;i++)
{
printf("Reference: ");
scanf("%d", &ref[i]);
ref[i]=nref;
code=fRecherche2(ref,n,nref);
printf("%d\n",code);
while(code!=-1)
{
printf("The reference already exists.\n");
printf("Please try again: ");
scanf("%d", &ref[i]);
ref[i]=nref;
code=fRecherche2(ref,n,nref);
printf("%d",code);
if(code==-1)
break;
}
fVerif(ref,i); //Checks if the value is bigger than 0
printf("Amount: ");
scanf("%d", &qt[i]);
fVerif(qt,i);
printf("Price: ");
scanf("%f", &prix[i]);
fVerifReal(prix,i); //Checks if the value is bigger than 0.00
printf("Security threshold: ");
scanf("%d", &sds[i]);
fVerif(sds,i);
}
fEnregNombre(nb); //saves my new size in a file
code=fEnreg(ref,qt,prix,sds,nb); // saves all my new arrays in a file
if(code==-1)
return -1;
}
void fCreerStock (void)
{
int i,n;
printf("Combien d'articles : ");
scanf("%d", &n );
while(n<=1)
{
printf("Il faut au moins 1 article!\n");
printf("Veuillez réesayer: ");
scanf("%d",&n);
if(n>0)
break;
}
FILE * nombre;
nombre=fopen("Nombre_d'article.txt","w");
if (nombre == NULL)
{
printf("probleme d'ouverture du fichier \n");
exit(1);
}
fprintf(nombre,"%d",n);
fclose(nombre);
int ref[n],qt [n], sds [n];
float prix[n];
for (i=0; i<n; i++)
{
printf("reference %d : ", i);
scanf("%d", &ref[i]);
fVerif(ref,i);
printf("quantité %d : ", i);
scanf("%d", &qt[i]);
fVerif(qt,i);
printf("Prix %d : ", i);
scanf("%f", &prix[i]);
fVerifReal(prix,i);
printf("seuil de sécurité %d : ", i);
scanf("%d", &sds[i]);
fVerif(sds,i);
}
FILE * flot;
flot=fopen("nom.txt","a");
if (flot == NULL)
{
printf("Probleme d'ouverture du fichier \n");
exit(1);
}
for (i=0; i<n; i++)
fprintf(flot,"%d\t%d\t%.2f\t%d\n",ref[i],qt[i],prix[i],sds[i]);
fclose(flot);
}
#include <stdio.h>
#include "sae.h"
void globale (void)
{
int n;
n=NbArticle();
int ref[n],qt[n],sds[n],CodeErr,code,CodeSup;
float prix[n];
char choix;
CodeErr=fConsulterStock(ref,qt,prix,sds,n);
printf("\n\nBienvenue a l'application de gestion de stock 'Xtrachaus'\n\n");
if (CodeErr== -1 || n == -1)
printf("!! Vous n'avez pas encore créer de stock veuillez créer un stock avant de faire n'importe quel manipulation !! \n\n");
printf("Créer un stock: 'c'| Afficher le stock: 'o'| Etat du stock: 'e'| Faire le devis d'une commade: 'd'| Récapitulatif des ventes: 'r'| Approvisionnement: 'a'| \nSupprimer un article:'s'| Rechercher un article avec n° ref: 'n'| Modifier l'article :'m'| Ajouter un article: 't'\n\n");
printf("Que voulez vous faire(votre choix): ");
scanf("%c%*c", &choix);
if (choix =='c')
fCreerStock();
if (choix =='o')
fAfficherStock(ref,qt,prix,sds,n);
if (choix =='e')
fEtatStock(ref,qt,prix,sds,n);
/*if (choix =='d')
fDevis();
if (choix =='r')
fVentes();*/
if (choix =='a')
{
fAfficherStock(ref,qt,prix,sds,n);
code=fAppro(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, l'approvisionement ne peut pas s'effectuer.\n");
else
printf("Approvisionement éffectué. \n");
printf("\n");
fAfficherStock(ref,qt,prix,sds,n);
}
if (choix =='s')
{
CodeSup=fSuppression(ref,qt,prix,sds,n);
if(CodeSup!=-1)
printf("Suppression éffectué. \n");
else
printf("Erreur, la suppression ne peut pas s'effectuer.\n");
}
if (choix =='n')
{
code=fRecherche(ref,n);
if (code!=-1)
{
printf("\nReference:\tQuantite:\tPrix:\tSeuil de securite:\n");
printf("%d\t\t%d\t\t%.2f\t\t%d\n" ,ref[code], qt[code], prix[code], sds[code]);
}
else
printf("La réference n'existe pas\n");
}
if (choix =='t')
{
code==fAjouter(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, l'ajout ne peut pas s'effectuer.\n");
else
printf("Ajout éffectué. \n");
}
if (choix =='m')
{
code=fModifier(ref,qt,prix,sds,n);
if(code==-1)
printf("Erreur, la modification ne peut pas s'effectuer.\n");
else
printf("Modification éffectué. \n");
}
}
int main (void)
{
globale();
return 0;
}
If theres anything else I could provide please tell me! Thanks.
(sorry most of the code and variables are in french i translated the part im stuck at).
edit3:
heres examples of where the program fails:
before adding a value:
https://imgur.com/XRbXvVl
After:
https://i.imgur.com/mRI1aJq.png (i choose 't' to add a value then type the how many i want to add, in this picture i wanted 1 more value, but i don't get to type my information, it immeadiatly adds random values)
https://imgur.com/HJk1PaW
One major problem: In the fAjouter function you have code like this
n=NbArticle();
nb=n+prods;
for(i=n+1;i<nb;i++)
{
printf("Reference: ");
scanf("%d", &ref[i]);
...
}
The array ref have n elements, and in the loop you start its indexing with n + 1.
Unless prods is equal to zero then i will start out of bounds of the array, and using it as an index will lead to undefined behavior.
Remember that array-size in C is fixed once the array is defined. C doesn't have dynamic arrays. If you need dynamic arrays whose size can be extended you need to use dynamic allocation with e.g. malloc and realloc.
I solved my problem by creating multiple arrays that will take will take the new size and will take the older values and ask the user to enter the new remaining ones.
void fVerifRef(int ref[],int ref2[], int n, int pos)
{
int j,val;
val=ref2[pos];
j=fRecherche2(ref,n,val);
while(j!=-1)
{
printf("Reference deja presente.\n");
printf("Veuillez réessayer: ");
scanf("%d",& ref2[pos]);
val=ref2[pos];
j=fRecherche2(ref,n,val);
if(j==-1)
break;
}
}
int fAjouter(int ref[],int qt[],float prix[],int sds[],int n)
{
int i,nb,prods,code;
printf("Combien de produits voulez vous ajouter:");
scanf("%d",& prods);
fVerifVal(&prods);
n=NbArticle();
nb=n+prods;
int ref2[nb],qt2[nb],sds2[nb];
float prix2[nb];
for(i=0;i<n;i++)
{
ref2[i]=ref[i];
qt2[i]=qt[i];
prix2[i]=prix[i];
sds2[i]=sds[i];
}
for (i=n; i<nb; i++)
{
printf("reference %d : ", i);
scanf("%d", &ref2[i]);
fVerifRef(ref,ref2,n,i);
/*fVerif(ref2,i);*/
printf("quantité %d : ", i);
scanf("%d", &qt2[i]);
fVerif(qt2,i);
printf("Prix %d : ", i);
scanf("%f", &prix2[i]);
fVerifReal(prix2,i);
printf("seuil de sécurité %d : ", i);
scanf("%d", &sds2[i]);
fVerif(sds2,i);
}
fEnregNombre(nb);
code=fEnreg(ref2,qt2,prix2,sds2,nb);
if(code==-1)
return -1;
}

Wrong matrix output when writing on csv file only for the first line [C]

I am writing a program that takes as input from the user names and answers associated for every candidate and print them on a .csv file as follow:
name, answer A, answer B,..., answer Z.
every name is stored in a matrix called nome_cognome;
every answer is stored in a matrix called matrice_risposte;
For some kind of reason I ignore, the program prints the wrong answer only for the last one of the first candidate (the "Z" question). Any other candidate has all the answers reported correctly.
what i tried to do:
I debugged the program for 5 days without understanding the reason behind the problem. I searched the web for similar issues, i tried to modify the code, but i cannot solve it.
I usually write on forums as my last chance, if i cannot find any kind of solution.
I make the user checks if the inserted answers are correct for every candidate before proceeding with the next one. When printing the answers on screen, they are reported correctly. When printing on file it happens as described.
The following image clearly show what i am talking about
I typed for Paul all the answers as 1, while for marie i typed all the answers as 2.
The code shows the section where the program writes on the csv file (it is created).
FILE *file_risultati; //apertura file di testo
strcat(corso,".csv");
file_risultati=fopen(corso, "w");
for (j=0;j<iscritti;j++){
p=0;
while(nome_cognome[j][p]!='\n')
{
fprintf(file_risultati,"%c", nome_cognome[j][p]);
p=p+1;
}
fprintf(file_risultati,",");
for(i=0; i<22; i++)
{
fprintf(file_risultati,"%d,", matrice_risposte[j][i]);
}
if(j != (iscritti-1)){
fprintf(file_risultati,"\n");
}
}
fclose(file_risultati); //chiusura file di testo
The following code is the complete program so you can check it all and verify what i said.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char corso[100];
char acquisizione_nome [40];
char domande[]= "ABCDEFGHIJLMNOPQRSTUVZ";
int iscritti;
int risposta;
int i;
int j;
int k=1;
int p;
// variabili variazione risposta
int modifica_risposta = 1;
int risposta_precedente;
char risposta_modificata;
char domande_min[]="abcdefghijlmnopqrstuvz";
int main()
{
printf("Program written by Gianluca Gregnol\n\n");
printf("Raccolta del fabbisogno formativo\n\n");
printf("Digitare il corso di interesse: ");
gets(corso);
printf("Digitare numero di iscritti al corso: ");
scanf("%d", &iscritti);
char nome_cognome[iscritti][40];
int matrice_risposte[iscritti][21];
// processo di inserimento votazioni //
for (k=0;k <(iscritti);k++)
{
printf("\n iscritto ");
printf("%d \n\n", k+1);
printf("nome e cognome: ");
fflush(stdin);
fgets(acquisizione_nome,40,stdin);
for (i=0; i<40; i++)
{
nome_cognome[k][i]= acquisizione_nome[i];
}
for (i=0; i<22; i++)
{
printf("\nvoto della domanda ");
printf("%c: ", domande[i]);
scanf("%d", &risposta);
while (risposta<0 || risposta>3)
{
printf("\n VOTO NON VALIDO!\n i voti validi sono: 0,1,2,3\n inserire nuovamente il voto per la domanda ");
printf("%c:", domande[i]);
fflush(stdin);
scanf("%d", &risposta);
}
matrice_risposte[k][i]=risposta;
}
//stampa le risposte attuali per permetterne il controllo
printf("\nLe risposte attualmente inserite sono: \n");
for (i=0; i<22; i++)
{
printf("%c ", domande[i]);
}
printf("\n");
for (i=0; i<22; i++)
{
printf("%d ", matrice_risposte[k][i]);
}
printf("\nDesideri modificare delle risposte? \n No = 0 \n Si = 1 \n");
printf("Risposta: ");
fflush(stdin);
scanf("%d", &modifica_risposta);
// controlla se l'utente vuole cambiare delle risposte
while(modifica_risposta == 1){
printf("\n\nQuale risposta vuoi modificare?\n");
printf("Risposta: ");
fflush(stdin);
scanf("%c", &risposta_modificata);
for(i=0; i<22; i++){
if(risposta_modificata == domande_min[i] || risposta_modificata == domande[i]){
printf("\nIndica il nuovo valore della domanda %c: ", domande[i]);
fflush(stdin);
scanf("%d", &risposta);
while (risposta < 0 || risposta > 3)
{
printf("\n VOTO NON VALIDO!\n i voti validi sono: 0,1,2,3\n inserire nuovamente il voto per la domanda ");
printf("%c:", domande[i]);
fflush(stdin);
scanf("%d", &risposta);
}
risposta_precedente = matrice_risposte[k][i] ;
matrice_risposte[k][i] = risposta;
printf(" -- Risposta modificata correttamente --\n\n");
}
}
printf("\nDesideri modificare delle risposte? \n No = 0 \n Si = 1 \n");
printf("Risposta: ");
fflush(stdin);
scanf("%d", &modifica_risposta);
} //main while
}
// processo scrittura su file
FILE *file_risultati; //apertura file di testo
strcat(corso,".csv");
file_risultati=fopen(corso, "w");
for (j=0;j<iscritti;j++){
p=0;
while(nome_cognome[j][p]!='\n')
{
fprintf(file_risultati,"%c", nome_cognome[j][p]);
p=p+1;
}
fprintf(file_risultati,",");
for(i=0; i<22; i++)
{
fprintf(file_risultati,"%d,", matrice_risposte[j][i]);
}
if(j != (iscritti-1)){
fprintf(file_risultati,"\n");
}
}
fclose(file_risultati); //chiusura file di testo
return 0;
}
Short answer:
in line 32:
int matrice_risposte[iscritti][21];
change 21 to 22
Explanation:
I noticed (from the attached picture) you have 22 questions but declared a 21 element array. In most languages multi-dimensional arrays are implemented by serialization. So matrice_risposte[1][22] is actually matrice_risposte[2][0]. You did not notice the bug because you first print the results then overwrite the last result with next round of input.

Can't delete the filename and can't rename my temporary file to database-aluno.txt

I'm trying to develop a solution for my algoritms and data structures subject. I have a function that takes a student through a comparison of the number read by a number that exists in my database (corresponds to the number of lines).
Happens right then the system enter the meal, which is only 1 for each day of each week. So far, no problems.
The system checks the balance of the student, and if the student has 0.0 balance or less than 3 balance (which is the cost of each meal) the system prompts or automatically recommends loading the balance, and mostly do all the steps correctly.
It turns out, that maybe due to several implemented cycles, I have almost everything to go well but at the end of the function instructions the instructions remove(filename); andrename("backup.c",filename);`
CODE:
void EncomendaRefeicoes()
{
FILE *myFile;
FILE *fin, *fout;//ficheiro de entrada ficheiro de saida
const char *fn = "database-aluno.txt";
myFile = fopen(filename, "r");
int num; //numero
rewind(myFile);
printf("Insrira o numero de aluno");//Ask of number
scanf("%d", &num);//read number
printf("\n A verificar se o aluno existe!");//Check
//procurar estudante
int fnum = 0;//student number in file
struct Aluno student;
char fnom[50];//student file name
char saldotostring[5];//
double saldo;//saldo
//int i=0;
while (!(feof(myFile)))//enquanto difrente de fim de ficheiro(feof)
{
fscanf(myFile, "%d %s %s %lf %d-%d\n", &Aluno[acstruct].num, Aluno[acstruct].name, Aluno[acstruct].fname, &Aluno[acstruct].saldo, &Aluno[acstruct].dia, &Aluno[acstruct].mes);
//file scan as variaveis num,name,saldo,dia,mes
if (num == Aluno[acstruct].num) //se num lido == num ficheiro
{
printf("\n");
printf("\n");
printf("Aluno %d encontrado", num);//Dizer que foi encontrado
printf("\n");
printf("Numero: %d", Aluno[acstruct].num);//imprime numero
printf("\n");
printf("Nome: %s", Aluno[acstruct].name);//imnprime nome
printf("\n");
printf("Subnome: %s", Aluno[acstruct].fname);
printf("\n");
//sprintf(saldotostring, "%.2f", saldo);
printf("Saldo: %.2f", Aluno[acstruct].saldo);//imprime saldo
printf("\n");
printf("Custo de aquisicao: 3.00 euros \n");//diz qual o custo de aquisicao
printf("\n");
//Menu
SelectOneFood(6, fp1);
printf("\n");
printf("Quer enconendar? \n");
printf("1-Reservar \n");
printf("\n");
printf("2-Mandar-me para o menu principal \n");
int opcaoescolhida;
scanf("%d", &opcaoescolhida);
double price = 3.00;
if (opcaoescolhida == 1)
{
if (Aluno[acstruct].saldo == 0.0)
{
char op = 'N';
printf("Nao tem saldo. Deseja carregar o plafound? (Primir N para nao) \n");
/*
if (scanf("%c", op) == 'N')
{
_tmain();
}
*/
printf("Valor a inserir: ");
printf("\n");
scanf("%lf", &saldo);
if (saldo < 5.00)
{
printf("Minimo de carregamento obrigatorio e de 5 euros \n");
scanf("%lf", &saldo);
}
fin = fopen(fn, "r");
fout = fopen("sbackup.txt", "w");//an temporary file
rewind(fin);
rewind(fout);
while (!(feof(fin))){
//Lê 1 a 1
fscanf(fin, "%d %s %s %lf %d-%d\n", &Aluno[acstruct].num, Aluno[acstruct].name, Aluno[acstruct].fname, &Aluno[acstruct].saldo, &Aluno[acstruct].dia, &Aluno[acstruct].mes);
if (num == Aluno[acstruct].num)
fprintf(fout, "%d %s %s %lf %d-%d\n", Aluno[acstruct].num, Aluno[acstruct].name, Aluno[acstruct].fname, saldo, Aluno[acstruct].dia, Aluno[acstruct].mes);
else if (num != Aluno[acstruct].num)
fprintf(fout, "%d %s %s %lf %d-%d\n", Aluno[acstruct].num, Aluno[acstruct].name, Aluno[acstruct].fname, Aluno[acstruct].saldo, Aluno[acstruct].dia, Aluno[acstruct].mes);
}
remove(filename);
rename("sbackup.txt",filename);
printf("\n");
printf("Saldo alterado");
fclose(fout);
fclose(myFile);
fclose(fin);
}
/*
if (Aluno[acstruct].saldo < price)
printf("Voce nao tem saldo suficiente \n");
*/
else if (Aluno[acstruct].saldo >= price)
{
Aluno[acstruct].saldo = Aluno[acstruct].saldo - price;
//substiruir saldo no ficheiro de texto
printf("Refeicao adequerida com sucesso \n");
printf("Saldo Final %.2f euros", Aluno[acstruct].saldo);
}
}
if (opcaoescolhida == 2)
_tmain();
}
}
}
How can I solve this problem? It will be a problem in if and while cycles?
Why don't you check the return value of remove() and in case of error, check the errno?
IMO, the problem is, you're calling remove() with the pointer of the file which is already fopen()ed and not yet fclose()d.

My program starts the loop before scan is done

I have a little problem, my program works well until it arrives to the final step, a scanf which asks for continuation of the loop. The problem is that this scan isn't working, but the following system("cls") works. Looks like javascript when async.
Here is the code.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char elegir_dificultad;
int dificil = 1;
printf("Desea que se le indique si el numero es menor o mayor? \n s/n \n");
scanf("%c",&elegir_dificultad);
if(elegir_dificultad == 's'){
dificil = 0;
}
while(1){
int aleatorio, cont, introducido;
cont = 1;
aleatorio = rand()%101;
printf("%d",aleatorio);
int fallo = 1;
while(fallo){
printf("Introduce el numero, intento numero %d \n", cont);
scanf("%d",&introducido);
if(introducido == aleatorio){
fallo = 0;
}
if(cont == 10){
break;
}
if(!dificil){
if(introducido < aleatorio){
printf("El numero introducido es menor que el aleatorio \n");
}
if(introducido > aleatorio){
printf("El numero introducido es mayor que el aleatorio \n");
}
}
if(fallo){
cont++;
}
}
char continuar;
if(fallo){
printf("Has perdido... el numero era %d \n Quieres repetirlo? s/n \n",aleatorio);
scanf("%c",&continuar);
if(continuar=='n'){
break;
}
system("cls");
}else{
printf("°Has ganado! el numero era %d \n Quieres repetirlo? s/n \n",aleatorio);
scanf("%c",&continuar);
if(continuar=='n'){
break;
}
system("cls");
}
}
system("PAUSE");
return 0;
}
This problem is because of \n character left behind by the previous scanf. Place a space before each %c specifier in scanf to eat up \n. .
scanf(" %c", &introducido);
...
scanf(" %c",&continuar);

Resources