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;
}
Related
So im doing this homework for my programming class, but the data output doesnt match with the theoretical data output that it shoud be printing and it gives me a big number.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void menu(int *);
void CalculoVentas(float ventas[50][7], float ventasXproductos[50], int);
void PromedioDiario(float promedioXdia[7], float ventas[50][7], int);
int main()
{
char ciclos;
int sel, cont = 0, i = 0;
float ventas[50][7], ventasXproductos[50], promedioXdia[7];
bool lectura = false;
while(sel != 5)
{
menu(&sel);
system("cls");
switch(sel)
{
case 1:
printf("Hay Productos?: S/N ");
fflush(stdin);
scanf("%c", &ciclos);
while(ciclos == 's' || ciclos == 'S' && cont < 50)
{
for(i=0;i<7;i++)
{
do
{
printf("Teclea los ingresos generados por el producto %d el dia %d: ", cont+1, i+1);
scanf("%f", &ventas[cont][i]);
}while(ventas[cont][i] < 0);
printf("\n\n");
}
cont++;
system("cls");
printf("Hay Productos?: S/N ");
fflush(stdin);
scanf("%c", &ciclos);
lectura = true;
}
break;
case 2:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
CalculoVentas(ventas, ventasXproductos, cont);
break;
case 3:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
PromedioDiario(promedioXdia, ventas, cont);
break;
case 4:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
printf("%35s\n", "Total de ventas");
for(i=0;i<cont;i++)
printf("%d %.2f\n", i+1, ventasXproductos[i]);
printf("\n\n\n\n");
printf("%35s\n", "Promedio de ventas por dia");
for(i=0;i<7;i++)
printf("Dia %d: %.2f\n", i+1, promedioXdia[i]);
printf("\n\n\n\n");
break;
}
}
}
void menu(int *seleccion)
{
printf("%20s\n%s\n%s\n%s\n%s\n%s\n", "Menu de opciones", "1.-lectura de datos", "2.-calculo de ventas por producto", "3.-promedio de ventas de cada dia", "4.-imprimir resultados", "5.-salir");
do{
printf("Seleccione una opcion: ");
scanf("%d", &*seleccion);
}while(*seleccion <= 0 || *seleccion > 5);
}
void CalculoVentas(float ventas[50][7], float ventasXproducto[50], int cont)
{
//realizar el calculo de ventas por productos, nada más es la suma de las ventas de todos los dias por producto
int i,j;
for (i = 0 ; i<cont ; i++)
for (j = 0 ; j < 7 ; j++)
ventasXproducto[i] = ventasXproducto[i] + ventas[i][j];
}
void PromedioDiario(float promedioXdia[7], float ventas[50][7], int cont)
{
int i,j;
for(i=0;i<7;i++)
{
for(j=0;j<cont; j++)
promedioXdia[i] = promedioXdia[i] + ventas[j][i];
promedioXdia[i] = promedioXdia[i]/cont;
}
}
the output is something like this, I try to type simple data so i can know easly if its wrong
Total de ventas
1 70.00
2 5103881324019006800000000000000000.00
3 210.00
4 280.00
Promedio de ventas por dia
Dia 1: 25.00
Dia 2: 25.00
Dia 3: 25.00
Dia 4: 1291386862541487300000000000000000.00
Dia 5: 25.00
Dia 6: -1.#R
Dia 7: 25.00
when i was trying to get help someone told me that i might be not initializing correctly the variables but i couldnt find any issue with that
When the program begins, sel is uninitialized and contains a garbage value. This garbage value is used in the while condition on its first iteration
while(sel != 5)
and as such invokes Undefined Behaviour.
You must restructure your loop to not read this uninitialized value, or simply initialize sel (to something other than 5).
Similarly, the contents of ventas, ventasXproductos, and promedioXdia are all uninitialized as well.
This means statements such as
ventasXproducto[i] = ventasXproducto[i] + ventas[i][j];
/* ... and ... */
promedioXdia[i] = promedioXdia[i]/cont;
will be operating with garbage values to start.
You can fix this by initializing your arrays:
float ventas[50][7] = { 0 }, ventasXproductos[50] = { 0 }, promedioXdia[7] = { 0 };
You should not ignore the return value of scanf. You should always check that its return value is the expected number of successful conversions, otherwise you will find yourself operating on incomplete data.
/* An example */
if (2 != scanf("%d%d", &num1, &num2)) {
/* handle failure */
}
(Better yet: avoid using scanf, and use fgets and sscanf to read and parse lines of input.)
You should clarify this expression by adding more parenthesis, otherwise you will run into issues with operator precedence:
while ((ciclos == 's' || ciclos == 'S') && cont < 50)
case 4 of the switch has misleading indentation. Only the first statement with the call to printf is contained within the else block. It is read as:
if(lectura == false)
printf("Primero ingresa los datos del producto!!!\n");
else
printf("%35s\n", "Total de ventas");
for(i=0;i<cont;i++)
printf("%d %.2f\n", i+1, ventasXproductos[i]);
/* ... */
Your lectura flag will not protect you from operating on incomplete data if this is selected. Enclose the code with curly braces:
case 4:
if(lectura == false) {
printf("Primero ingresa los datos del producto!!!\n");
} else {
printf("%35s\n", "Total de ventas");
for(i=0;i<cont;i++)
printf("%d %.2f\n", i+1, ventasXproductos[i]);
/* ... */
}
break;
Note that in &*seleccion, & and * balance each other out. This resolves to the same value as just writing seleccion would.
Note that fflush(stdin); is also (technically) Undefined Behaviour, and should not be relied upon.
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);
}
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.
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.
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);