How to validate if there is the same info in a struct? - c

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!

Related

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;

Why does the "for" loop not work and program stops?

When I compile the program it seems to work normally but, when it asks for the "cuadrados", the program just stops:
int main(){
int *ptrs, suma=0, n, i, m;
printf("cuantos numeros al cuadrado quiere?: ");
scanf("%i", &n);
int numero[n], cubo[n];
*ptrs=numero
Here is when the program stops:
for(i=0;i<n;i++){
printf("escriba los cuadrados: ");
scanf("%i", numero[i]);
}
printf("Cuantos numero al cubo quiere?: ");
scanf("%i", m);
for(i=0;i<n;i++){
printf("escriba los cubos: ");
scanf("%i", cubo[i]);
}
I had this issue before but I can't understand why it does not keep running; it just asks for 1 number and then stops with no error or warning.
for(i=0;i<n;i++){
printf("escriba los cuadrados: ");
scanf("%i", &numero[i]);
}
printf("Cuantos numero al cubo quiere?: ");
scanf("%i", &m);
for(i=0;i<n;i++){
printf("escriba los cubos: ");
scanf("%i", &cubo[i]);
}
You need to give address of the variable in scanf using & operator
This will crash because scanf needs a pointer-to-int, not an int:
scanf("%i", numero[i]);
This will not:
if (scanf("%i", &numero[i]) == 1) {
/* do something */
}
else {
/* scanf failed */
}
Note that not testing the scanf return value is always asking for trouble. As is not using your compiler's maximum warning level and turning all warnings into errors.

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.

Passing parameters struct to function in C

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 &.

passing arg 1 of `puts' makes pointer from integer without a cast

struct{
char nome[30],rua [50],bairro [20],cidade [30],se [3] ;
int na, exc, numero;
long int CEP;
}typedef endereco;
main(){
endereco agenda[20];
int i, j, opc, opc1=0, opc2, eopc ;
char pnome[30], pbairro[20], pcidade[30], enome[30];
while (opc!=4){
system("cls");
printf("Agenda facs, digite a opção: \n|\t1-incluir\t|\n|\t2-Consultar\t|\n|\t3-excluir\t|\n|\t4-sair\t |\nDigite a opção ");
scanf("%d",&opc);
fflush(stdin);
switch (opc){
case 1:
system("cls");
printf("Digite os Dados a seguir para incluir no # %d :\n",opc1+1);
agenda[opc1].na=opc1+1;
agenda[opc1].exc=0;
printf("Digite o nome: ");
gets(agenda[opc1].nome);
printf("Digite a Rua: ");
gets(agenda[opc1].rua);
printf("Digite o Bairro: ");
gets(agenda[opc1].bairro);
printf("Digite o numero: ");
fflush(stdin);
scanf("%d",&agenda[opc1].numero);
fflush(stdin);
printf("Digite a Cidade: ");
gets(agenda[opc1].cidade);
printf("Digite a Sigla do Estado: ");
gets(agenda[opc1].se);
printf("Digite o CEP: ");
fflush(stdin);
scanf("%d",&agenda[opc1].CEP);
fflush(stdin);
opc1++;
break;
case 2:
system("cls");
printf("\n|\t1-Nome\t|\n|\t2-Bairro\t|\n|\t3-Cidade\t|\n|\tDigite a opção ");
scanf("%d",&opc2);
printf("\t|\n");
fflush(stdin);
switch (opc2){
case 1:
system("cls");
printf("Qual o nome a procurar? ");
gets(pnome);
for(i=0;i<20;i++){
if(strcmp(pnome,agenda[i].nome)==0){
printf("\n\tNumero Agenda: ");
puts(agenda[i].na); printf("\n\tNome: ");
printf("\n\tNome: ");
puts(agenda[i].nome);
printf("\n\tRua: ");
puts(agenda[i].rua);
printf("\n\tBairro: ");
puts(agenda[i].bairro);
printf("\n\tNumero: ");
puts(agenda[i].numero);
printf("\n\tCidade: ");
puts(agenda[i].cidade);
printf("\n\tEstado: ");
puts(agenda[i].se);
printf("\n\tCEP: ");
puts(agenda[i].CEP);
printf("\n\t______________");}}
break;
case 2:
system("cls");
printf("Qual o Bairro a procurar? ");
gets(pbairro);
for(i=0;i<20;i++){
if(strcmp(pbairro,agenda[i].bairro)==0){
printf("\n\tNumero Agenda: ");
puts(agenda[i].na); printf("\n\tNome: ");
printf("\n\tNome: ");
puts(agenda[i].nome);
printf("\n\tRua: ");
puts(agenda[i].rua);
printf("\n\tBairro: ");
puts(agenda[i].bairro);
printf("\n\tNumero: ");
puts(agenda[i].numero);
printf("\n\tCidade: ");
puts(agenda[i].cidade);
printf("\n\tEstado: ");
puts(agenda[i].se);
printf("\n\tCEP: ");
puts(agenda[i].CEP);
printf("\n\t______________");}}
break;
case 3:
system("cls");
printf("Qual a Cidade a procurar? ");
gets(pcidade);
for(i=0;i<20;i++){
if(strcmp(pbairro,agenda[i].cidade)==0){
printf("\n\tNumero Agenda: ");
puts(agenda[i].na);
printf("\n\tNome: ");
puts(agenda[i].nome);
printf("\n\tRua: ");
puts(agenda[i].rua);
printf("\n\tBairro: ");
puts(agenda[i].bairro);
printf("\n\tNumero: ");
puts(agenda[i].numero);
printf("\n\tCidade: ");
puts(agenda[i].cidade);
printf("\n\tEstado: ");
puts(agenda[i].se);
printf("\n\tCEP: ");
puts(agenda[i].CEP);
printf("\n\t______________");}}
break;}
case 3:
system("cls");
printf("Digite o Numero da Agenda que deseja excluir");
gets(enome);
for(i=0;i<20;i++){
if(strcmp(enome,agenda[i].nome)==0){
printf("\n\tNumero Agenda: ");
puts(agenda[i].na);
printf("\n\tNome: ");
puts(agenda[i].nome);
printf("\n\tRua: ");
puts(agenda[i].rua);
printf("\n\tBairro: ");
puts(agenda[i].bairro);
printf("\n\tNumero: ");
puts(agenda[i].numero);
printf("\n\tCidade: ");
puts(agenda[i].cidade);
printf("\n\tEstado: ");
puts(agenda[i].se);
printf("\n\tCEP: ");
puts(agenda[i].CEP);
printf("\n\t______________");}}
printf("\n\tDigite o Numero Agenda do Nome na qual voce quer excluir: ");
fflush(stdin);
scanf("%d",&i);
fflush(stdin);
if(agenda[i].exc==0){
printf("\n\t%d . %s \n\tDeseja excluir esse contato?\n\t1-Sim\n\t2-Nao\n\tOpcao: ",agenda[i].na,agenda[i].nome);
fflush(stdin);
scanf("%d",&eopc);
fflush(stdin);
switch (eopc){
case 1:
agenda[i].exc=1;
printf("\t\nNumero excluido !");
break;
case 2:
printf("\t\nNumero nao excluido !");
break;}}}}
system("PAUSE");
return 0;
}
Hello :D
This program was build, or trying to, be a notebook that you can save contacts.
But i'm getting this warning, and when the 'puts' come in the program, it crashes.
Someone can help ?
[Warning] passing arg 1 of `puts' makes pointer from integer without a
cast
Thanks.
puts(agenda[i].na);
In your code agenda[i].na is an int. You can't print it with puts, try printf:
printf("%d\n", agenda[i].na);
and when the 'puts' come in the program, it crashes.
You are tricking puts into using a random integer as a pointer.

Resources