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;
Related
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.
i have constructed a program that makes basic calculations of a number the user enters before closing. homewever, i would like to make the program ask the user if he wants to input another number and closing if he says no. here is the program for reference. it asks for four numbers, then sums then:
#include<stdlib.h>
int main(void)
{
float n1, n2, n3,n4, resultado;
printf("insira o primeiro numero: ");
scanf("%f",&n1);
printf("insira o segundo numero: ");
scanf("%f",&n2);
printf("insira o terceiro numero: ");
scanf("%f",&n3);
printf("insira o quarto numero: ");
scanf("%f",&n4);
resultado = (n1 + n2 + n3 + n4) ;
printf(" A total soma dos numeros eh = %.1f\n",resultado);
return 0;
}```
You can simply surround your code with do while loop, try something like this:
int main() {
int user_response;
do {
// rest of your code here
printf("Would you like to do another calculation? (1 - yes, 0 - no) ");
scanf("%d", &user_response);
} while (user_response == 1);
return 0;
}
Im doing a struct to register students´ info, previously I asked the user how many he wanted to register and proceeded to do it with a for loop:
case 1:
printf("How many students you want to register?:(no more than 10) \n");
scanf("%d", &num);
fflush(stdin);
printf("\n");
for(int i=0;i<num;i++){
alumno[i]=llenarInfo(alumno[i]);
}
printf("---------------------\n");
but how can I do it 1 at a time? I tried increasing i after the loop for but if I register 2 or more and want to print them all it only prints the last one and when asking for the name of the student (atm of filling the info) it automatically jumps to the next member of the struct:
struct Usuario llenarInfo(struct Usuario alumno){
printf("Dame el nombre: ");
gets(alumno.nombre);
fflush(stdin);
printf("");
jumps this^^
printf("Dame el codigo de alumno: ");
scanf("%d", alumno.codigo);
fflush(stdin);
printf("");
printf("Dame el email: ");
scanf("%s", alumno.email);
fflush(stdin);
printf("");
printf("Que carrera estudia?: ");
scanf("%s", alumno.carrera);
fflush(stdin);
printf("");
printf("Cual es el sexo? H Hombre- M Mujer: ");
scanf("%s", alumno.sexo);
fflush(stdin);
printf("");
printf("Cual es la edad?: ");
scanf("%s", alumno.edad);
fflush(stdin);
printf("\n");
return alumno;
but how can i do it 1 at a time?
from your question I think the fflush is not working
you can define a simple flush function to use it instead
void _flush() {
int c;
while((c = fgetc(stdin)) != EOF) {
if(c == '\n') break;
}
}
besides you should use fgets instead of gets, because gets doesn't check for overflows and that makes it dangerous, and it's no more in C standard!
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 am System Analyst & Developer student, I'm trying to write code but I'm stuck, structs and fuctions are easy to understand but working with both together... is a... crap...
What an I doing wrong?
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
typedef struct mercearia
{
char mercadoria[20];
int quantidade;
int valor;
} mercearia;
void EstruturaCadastro(struct mercearia *m)
{
int i;
for(i = 0; i < 5; i++)
{
printf("\n");
setbuf(NULL, stdin);
printf("Insira nome do produto a cadastrar: ");
scanf("%s", &(*m)[i].mercadoria);
setbuf(NULL, stdin);
printf("Insira a quantidade do produto: ");
scanf("%i", &(*m)[i].quantidade);
setbuf(NULL, stdin);
printf("Insira o valor do produto: R$ ");
scanf("%i", &(*m)[i].valor);
}
}
int main(void)
{
setlocale(LC_ALL, "");
struct mercearia m[5];
EstruturaCadastro(&m);
}
It gives me huge error list. Then I wrote same code but without creating array of struct and the code worked perfectly. I am missing up something.
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
typedef struct mercearia
{
char mercadoria[20];
int quantidade;
int valor;
} mercearia;
void EstruturaCadastro(struct mercearia *x)
{
printf("\n");
printf("Insira nome do produto: ");
scanf("%s", &(*x).mercadoria);setbuf(NULL, stdin);
printf("Insira a quantidade do produto: ");
scanf("%i", &(*x).quantidade);setbuf(NULL, stdin);
printf("Insira o valor do produto: R$ ");
scanf("%i", &(*x).valor);setbuf(NULL, stdin);
}
int main(void)
{
setlocale(LC_ALL, "");
struct mercearia produto;
EstruturaCadastro(&produto);
}
You need to understand the 2nd example (simple) before trying the 1st (harder)
void EstruturaCadastro(struct mercearia *x)
{
printf("\n");
printf("Insira nome do produto: ");
scanf("%s", x->mercadoria);
printf("Insira a quantidade do produto: ");
scanf("%i", &x->quantidade);
printf("Insira o valor do produto: R$ ");
scanf("%i", &x->valor);
}
No need for the setbuf() call, you flush stdin when you press the key
Once you've done this, you can change to m[i]->mercadoria, etc in your first example.
There are all kinds of wrong with your original function. You're passing it a pointer to struct mercearia which is fine for passing in your array. Inside the function you can treat m the same way you would an array, so for example m[0].valor is how you'd access the valor value for the first element.
This means that your various calls to scanf become
scanf("%s", m[i].mercadoria);
scanf("%i", &m[i].quantidade);
scanf("%i", &m[i].valor);
Note, that for reading in a string unlike other data types, you don't need to pass in the pointer to the string so you don't need the preceeding &.