Why positive values turns negative - c

I'm making some tests writing in a file.
Every single value numerical turns negative for no reason and i wont that.
I put for example: codigo : 1 and it always show the number -13312 , or codigo : 2 and the output is : -13312
How can i fix it?
#include <stdio.h>
int main() {
int codigo1[100];
int numero_telefone[100];
int numero_dependentes[100];
char nome[100];
char estado_civil[100];
FILE *fp;
if ((fp = fopen("nomes.txt", "a")) != NULL) {
printf("Indique o seu codigo de funcionario [0-100]: ");
scanf("%d", codigo1);
fprintf(fp, "Codigo funcionario: %d \n", codigo1);
printf("Inroduduza o seu nome: ");
scanf(" %s", nome);
fprintf(fp, "Nome: %s \n", nome);
printf("Insira o seu numero de telefone: ");
scanf("%d", &numero_telefone);
fprintf(fp, "Numero de telefone: %d \n", numero_telefone);
printf("Indique o seu estado civil: ");
scanf(" %s", &estado_civil);
fprintf(fp, "Estado civil: %s \n", estado_civil);
printf("Indique o numero de dependentes: ");
scanf("%d", &numero_dependentes);
fprintf(fp, "Numero dependentes: %d \n", numero_dependentes);
}
fclose(fp);
}

codigo is defined as an array of 100 integers. Which means it's essentially a pointer when passed to another function.
In this statement:
scanf("%d", codigo1);
codigo1[0] gets filled with the typed integer. The other 99 values inside that array are undefined. But codigo1[0] is assigned correctly.
But this statement:
fprintf(fp, "Codigo funcionario: %d \n", codigo1);
Is pushing the address of codigo1 onto the stack and the %d format specifier is used to interpret it as an integer. Also, a stack alignment issue if sizeof(&int) != sizeof(int) which is usually the case on 64-bit platforms. That can cause problems with printf statements using multiple format specifiers with corresponding parameters.
The easy fix is to pass the specific integer value you want to write to file:
fprintf(fp, "Codigo funcionario: %d \n", codigo1[0]);
Similar treatment is needed for your other statements. You should also consider if you really need to use arrays. The following works just as well:
int codigo1 = 0;
...
scanf("%d", &codigo1); // &codigo1 is the "address of" codigo1
fprintf(fp, "Codigo funcionario: %d \n", codigo1);

Related

Having issues to printf numbers in this typedef struct algorithm

Im doing this struct to print the register of some people i want to register, saving in a array and printing but when i used float it was printing a memory dump and now the int numbers are becoming memory dump too
#include <stdio.h>
typedef struct{
int id_insc[20];
char nome[50];
char altura[10];
int peso[8];
char naturalidade[15];
char estado[10];
} Empregado;
main(){
Empregado empregado[3];
int i;
for(i=0;i<3;i++){
printf("1. Digite o ID da inscricao\n");
scanf("%d", empregado[i].id_insc);
printf("2. Digite o nome do candidato(a)\n");
scanf("%s", empregado[i].nome);
printf("3. Digite a altura\n");
scanf("%s", empregado[i].altura);
printf("4. Digite o peso do candidato (sem casas decimais)\n");
scanf("%d", empregado[i].peso);
printf("5. Digite a naturalidade do candidato(a)\n");
scanf("%s", empregado[i].naturalidade);
printf("6. Digite o estado do candidato(a)\n");
scanf("%s", empregado[i].estado);
system("cls");
}
system("cls");
for(i=0;i<3;i++){
printf(" Id: %d\n Nome: %s\n Altura: %s\n Peso: %d\n Naturalidade: %s\n Estado: %s\n",
empregado[i].id_insc,
empregado[i].nome,
empregado[i].altura,
empregado[i].peso,
empregado[i].naturalidade,
empregado[i].estado);
printf("\n");
}
}
Id: 6487160
Nome: gustavo
Altura: 180
Peso: 6487300
Naturalidade: brasileiro
Estado: parana
the output is printing like this and i typed 11 and 60
For starters in this calls of scanf
printf("1. Digite o ID da inscricao\n");
scanf("%d", empregado[i].id_insc);
printf("4. Digite o peso do candidato (sem casas decimais)\n");
scanf("%d", empregado[i].peso);
you entered only the first elements of the data member arrays
int id_insc[20];
and
int peso[8];
That is these calls of scanf
scanf("%d", empregado[i].id_insc);
and
scanf("%d", empregado[i].peso);
are equivalent to
scanf("%d", &empregado[i].id_insc[0]);
and
scanf("%d", &empregado[i].peso[0] );
because arrays used in expressions with rare exceptions are converted to pointers to their first elements. You can not to enter all elements of an integer array using only one format string "%d".
If you want to enter values for all elements of the arrays you need to use one more for loop.
To output them in the call of printf you have to specify these arguments
empregado[i].id_insc[0],
and
empregado[i].peso[0],
instead of
empregado[i].id_insc,
and
empregado[i].peso,
Again you can not use one conversion specifier %d to output all elements of an integer array. You need to use additional loops. The conversion specifier %d used in a call of printf expects a scalar object of the type int.

How do I make my code printf increment from 0 every loop?

I want to make a sort of food ordering system, but whenever I try to make the ID increment by 1 every loop, it doesn't work. It just shows the number 6684076, no matter what.
Here's the code:
struct res {
char nome[40];
char endereco[100];
char pedido[200];
char valor[20];
};
int main() {
char M[100];
int c;
int menu;
int cod = 0;
while (cod < 100) {
cod = cod + 1;
struct res R1, R2, R3, R4;
printf("Digite seu nome: \n");
gets(R1.nome);
fflush(stdin);
printf("Digite seu endereco: \n");
gets(R2.endereco);
fflush(stdin);
printf("Digite seu pedido: \n");
gets(R3.pedido);
fflush(stdin);
printf("Digite o valor total que vai pagar: \n");
gets(R4.valor);
fflush(stdin);
system("cls");
c = c + 1;
printf("Codigo: %d\n", &c);
printf("Nome: %s\n", R1.nome);
printf("Endereco: %s\n", R2.endereco);
printf("Pedido: %s\n", R3.pedido);
printf("Valor: %s\n", R4.valor);
}
return 0;
}
you should've initialised int c to 0 otherwise it'll take a garbage value
I don't see any errors in my compiler and when I debug it, there's no issue with the value of c, so I changed the
printf("Codigo: %d\n", &c);
statment with
printf("Codigo: %d\n", c);
and the output has no issues:
Codigo: 1
Nome: ab
Endereco: cd
Pedido: ef
Valor: gh
Digite seu nome:
EDIT: Additionally you need to initialise c with a meaningful value, e.g. 0, otherwise it might contain a garbage value and reading it provokes undefined behaviour:
int c = 0;

it shows output more than 4 times

I was trying to make a program in C that basically asks the user some information about the people they live with. The code is in Spanish, but I will show you the problem.
/*Miembros de la familia*/
#include<stdio.h>
#include<stdbool.h>
#define TRUE 1
#define FALSE 0
int main(){
int personas,i,varones=0,hembras=0,opcion;
bool mayoredad=false;
printf("Indique cuantas personas viven en su casa:\n");
scanf("%i", &personas);
struct nombre{
char primer[30];
char segundo[30];
char apellido[30];
}minombre;
struct fecha{
int dia;
int mes;
int anio;
}nacimiento, actual;
printf("\nIngrese la fecha actual:\n");
scanf("%i %i %i", &actual.dia, &actual.mes, &actual.anio);
struct familia{
struct nombre minombre;
char cedula[10];
struct fecha nacimiento;
char genero;
int edad;
}familia[personas];
for(i=0;i<personas;i++){
printf("\nIndique su primer nombre, segundo nombre y apellido:\n");
scanf("%s %s %s", &familia[i].minombre.primer, &familia[i].minombre.segundo, &familia[i].minombre.apellido);
printf("\nPor favor escriba su numero de cedula:\n");
scanf("%s", &familia[i].cedula);
do{
printf("\nIngrese la fecha de su nacimiento: (DD)(MM)(AAAA):\n");
scanf("%i %i %i", &familia[i].nacimiento.dia, &familia[i].nacimiento.mes, &familia[i].nacimiento.anio);
if(familia[i].nacimiento.anio>actual.anio){
printf("Dato invalido, por favor intente nuevamente.");
}
}while(nacimiento.anio>actual.anio);
familia[i].edad=actual.anio-familia[i].nacimiento.anio;
if(familia[i].nacimiento.mes>=actual.mes && familia[i].nacimiento.dia>actual.dia){
familia[i].edad--;
}
if(familia[i].edad>=18){
mayoredad=true;
}
do{
printf("Indique su genero: (f) o (m):");
scanf(" %c", &familia[i].genero);
if(familia[i].genero=='f'){
hembras++;
}else if(familia[i].genero=='m'){
varones++;
}
}while(familia[i].genero!='f' && familia[i].genero!='m');
}
do{
printf("Registro concluido. Desea ver las estadisticas? 1(si) 2(no)");
scanf("%i", &opcion);
if(opcion!=1 && opcion!=2){
printf("DATO INVALIDO, INTENTE NUEVAMENTE");
}else if(opcion==1){
for(i=0;i<personas;i++){
printf("Nombre: %s %s %s\n", familia[i].minombre.primer, familia[i].minombre.segundo, familia[i].minombre.apellido);
printf("Cedula:%s\n", familia[i].cedula);
printf("Edad:%i\n", familia[i].edad);
printf("Mayor de edad:\n");
switch(mayoredad){
case true:printf("Si");break;
case false:printf("No");
}
}
printf("Cantidad de personas en el hogar: %i\n", personas);
printf("Varones: %i Hembras: %i\n", varones, hembras);
}
}while(opcion>=2 && opcion<0);
printf("Presione una tecla para salir.");
getchar();
return 0;
}
In the last do-while loop that requests the person's gender (familia[i].genero)
It is supposed to ask just once, but in the last iteration of the for loop, it displays the same question four times:enter image description here
How can I fix this?
The format specifier %i will treat input whose suffix is 0 (and not 0x nor 0X) as octal number.
Therefore, 09 in your input is invalid as octal number and it will leave 9 in the stream.
This 9 is read to familia[i].nacimiento.anio by the next specifier.
Then, following scanf(" %c", &familia[i].genero); will read 2003 from the input and this will lead to the 4 extra asking.
To fix this, use %d specifier to read integers. %d spcifier will treat input as decimal number regardless of the suffix.

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.

read from .txt C

I'm having some trouble with C language..
I have one file txt with various lines in the form:
F 65 S 4 1 139.56 3704.26
and my program:
p = fopen("dados.txt", "r");
if ( p == NULL) {
printf("\n\nNao foi possivel abrir o arquivo.\n");
exit(1);
}else{
while ( !feof(p) ){
fscanf(p,"%c %d %c %d %d %f %f",
&sexo,&idade,&estadoCivil,&numFilhos,&freq,&mediaGasto,&mediaSalarial);
printf("%c %d %c %d %d %f %f\n",
sexo,idade,estadoCivil,numFilhos,freq,mediaGasto,mediaSalarial);
}
the return is:
looks bad...
if i change in fscanf: %c to %f
the return is:
looks great, but the variable idade is always 0... :S
wtf i have to do?
You have to add the newline to your scanf call:
fscanf(p,"%c %d %c %d %d %f %f\n",
&sexo,&idade,&estadoCivil,&numFilhos,&freq,&mediaGasto,&mediaSalarial);
Without the newline in scanf, the first line will be correct, but the following line assigns the newline from the input to sexo.

Resources