Storing and printing a struct array doesnt work as expected - c

First of all, I want to explain my vocabulary of functions:
Universo: Universe
Edad: Age
Nombre: Name
Alias: Nickname
Nacionalidad: Country
Persona: Person
Insertar persona: Add Person to the Struct array
Mostrar persona: Print all the struct array elements
So I want to create a struct array and an options table in where I can choose to add persons or print them. The program max person capacity is 1000 and it checks if the person is already in the array or not, adding ir if so.
So I don't understand in first place why it doesnt print all the persons and if the persons actually are stored. Can you help me? It is a class work and I can't complicate it more that, so pointers aren't allowed. This is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CAD 100
#include <string.h>
#include <ctype.h>
struct persona{
char nombre[MAX_CAD];
int edad;
char nacionalidad[MAX_CAD];
char alias[MAX_CAD];
};
int insertarPersona(struct persona universo[], int capacidad_max, struct persona nueva);
void mostrarMundo(struct persona universo[], int capacidad_max);
int main()
{
int seleccion, capacidadmax=1000, i=0;
struct persona universo[1000];
struct persona nueva;
strcpy(universo[i].nombre, "-");
strcpy(universo[i].nacionalidad, "-");
strcpy(universo[i].alias, "-");
universo[i].edad = -1;
do{
printf("1-Crear persona \^\// \n");
printf("2-Mostrar universo |. .| \n");
printf("3-Thanos-Chascar _ \ - / _ \n");
printf("4-Restaurar universo \_| |_/ \n");
printf("5-Salir \ \ \n");
printf(" __/_/__\n");
printf(" | |\n");
printf(" \ /\n");
printf(" \___/\n");
scanf("%d", &seleccion);
if(seleccion==1&&i<1000){
printf("Introduzca el nombre de la persona a añadir\n");
while(getchar()!='\n');
gets(nueva.nombre);
printf("Introduzca el alias de la persona a añadir\n");
gets(nueva.alias);
printf("Introduzca la nacionalidad de la persona a añadir\n");
gets(nueva.nacionalidad);
printf("Introduzca la edad de la persona a añadir\n");
scanf("%d", &nueva.edad);
if(insertarPersona(universo, capacidadmax, nueva)==1){
strcpy(universo[i].nombre, nueva.nombre);
strcpy(universo[i].alias, nueva.alias);
strcpy(universo[i].nacionalidad, nueva.nacionalidad);
universo[i].edad=nueva.edad;
printf("Persona añadida!\n");
i++;
}
else{
printf("El universo esta lleno o dicha persona ya esta dentro\n");
}
}else if(seleccion==2){
printf("pers. Nombre\t\t\t\t\t Alias\t\t\t\t Nacionalidad\t\t\t Edad\n");
printf("=====================================================================================================================\n");
mostrarMundo(universo, capacidadmax);
}
printf("%d",i);
}while (seleccion !=5);
return 0;
}
int insertarPersona(struct persona universo[], int capacidad_max, struct persona nueva){
capacidad_max=1000;
int espersona=0;
for(int i=0; i=='\0'&& i<capacidad_max;i++){
if ((strcmp(nueva.nombre, universo[i].nombre)&& (nueva.edad!=universo[i].edad)&& strcmp(nueva.nacionalidad, universo[i].nacionalidad)&& strcmp(nueva.alias, universo[i].alias)) !=0 && i<1000){
espersona=1;
}else {
espersona=0;
}
}
return espersona;
}
void mostrarMundo(struct persona universo[], int capacidad_max){
capacidad_max=1000;
for(int i=0; i=='\0'&&i<capacidad_max; i++){
printf("%d\t%-35s%-25s\t%-20s%10d\n", i+1, universo[i].nombre, universo[i].alias, universo[i].nacionalidad, universo[i].edad);
if(universo==0){
printf("Universo no habitado\n");
}
}
}

Related

how to solve the error (expected identifier before'(' token) in C

its my first question here..
In the following code. It keeps giving me the following error in the scanf lines: Expected identifier before '(' token.
i dont know how to solve it..
typedef struct avion
{
int code;
int capacite;
char etat[1];
int date;
int nvols;
} avion;
typedef struct element *list;
typedef struct element
{
avion A;
struct element *svt;
} element;
list *Modifier(list* av)
{
list *p=av;
int c;
printf("\n------------La Modification--------------\n");
printf("\nDonner le code de l'avion que vous voulez modifier... :");
scanf("%d",&c);
while(av!=NULL)
{
if ((av->(A.code)) == c)
{
printf("\nL'avion existe dans la liste...");
printf("\nDonner le nouveau code:");
scanf("%d",&av->(A.code));
printf("\nDonner la nouvelle capacite...:");
scanf("%d",av->(A.capacite));
printf("\nDonner le nouveau etat...:");
scanf("%s",av->(A.etat));
printf("\nDonner la nouvelle date de fabrication...:");
scanf("%d",av->(A.date));
printf("\nDonner le nouveau nombre de vols assures...:");
scanf("%d",(av->(A.nvols)));
return p;
}
(*p)=p ->(svt);
}
}
The "expected identifier before '(' token" error occurs because you are using -> operator to access a field of a struct and, instead of passing the field identifier, you are passing a '(' character.
Here is the list of errors.
av->(A.code) is bad syntax. If av is a pointer to a struct
that contains a struct field called A and you want to access the
field code of A, use av->A.code;
(*p) = p->(svt) is also bad syntax. If you want p to point to
the next element of the list, witch I assumed is pointed by the
field svt, use p = p->svt;
You forgot to pass the address of your integers when you use
scanf() with "%d" identifier, inserting the '&' character
before the variable names;
Replace typedef struct element *list for typedef struct element list;
Note that the function will return after the first element on whose
code field equals c. If you meant to do that, you need to return
a list * after the while loop. I suggest you to return NULL to
signalize no element of the list was modified.
Here is my suggestion.
#include <stdlib.h>
#include <stdio.h>
typedef struct avion {
int code;
int capacite;
char etat[1];
int date;
int nvols;
} avion;
typedef struct element {
avion A;
struct element *svt;
} element;
typedef struct element list;
list *modifier(list* av) {
list *p=av;
int c;
printf("\n------------La Modification--------------\n");
printf("\nDonner le code de l'avion que vous voulez modifier...: ");
scanf("%d", &c);
while (av!=NULL) {
if (av->A.code == c) {
printf("\nL'avion existe dans la liste...");
printf("\nDonner le nouveau code: ");
scanf("%d", &av->A.code);
printf("\nDonner la nouvelle capacite...: ");
scanf("%d", &av->A.capacite);
printf("\nDonner le nouveau etat...: ");
scanf("%s", av->A.etat);
printf("\nDonner la nouvelle date de fabrication...: ");
scanf("%d", &av->A.date);
printf("\nDonner le nouveau nombre de vols assures...: ");
scanf("%d", &av->A.nvols);
return p;
}
p = p->svt;
}
return NULL;
}
Surprisingly (or not), the same error appears if you have say
#define VALUE
and then, later
if (VALUE) {
// do something
}
The solution is to define it with an actual value, like
#define VALUE (1)

C structures and functions

I'm new to C programming and I am trying to create a function that adds values to a structure but it does not return anything.
This function is meant to allow the user to add records.
#include <stdio.h>
#include <string.h>
struct Produit {
int Num;
char Nom[50];
char Description[100];
float Prix;
} s[10];
void add(struct Produit s[],int n);
void display(struct Produit s[],int p,int n)
int main {
add(s,1);
display(s,1);
++n;
}
void add(struct Produit s[], int n){
again:
printf("\nEntrez le nom du produit à ajouter:");
scanf("%s",s[n].Nom);
if(searchP(s,s[n].Nom,n)!=-1){
printf("Déjà existant\n");goto again;
}
printf("Entrez la description :");
scanf("%s",&s[n].Description);
printf("Entrez le prix :");
scanf("%f",&s[n].Prix);
}
void display(struct Produit s[],int p,int n) {
printf("Nom du produit: ");
puts(s[p-1].Nom);
printf("Description: ");
puts(s[p-1].Description);
printf("Prix: %.1f", s[p-1].Prix);
printf("\n");
}
When I run this it works fine but when I verify if the record that I've entered is is there I don't find anything. I try to display the record but it's empty.
it returns this :
Entrez le nom du produit α ajouter:pen
Entrez la description :red
Entrez le prix :1.99
Nom du produit:
Description:
Prix: 0.0
can anyone tell what is wrong. thanks
PS : The function SearchP is working fine in other parts of the code so I don't think it is the problem, but nonetheless here is it.
int searchP(struct Produit s[],char Name[], int n) {
int found =-1,i;
for (i = 0; i < n-1 && found==-1; i++)
{
if (strcmp(s[i].Nom,Name)==0) {
found=i;
}
else
found=-1;
}
return found;
}
Here is a modified version of your code that works better but still needs some work.
As already commented you need a global counter for the s array (here: nbp).
There also one-off errors when searching into s.
#include <stdio.h>
#include <string.h>
struct Produit {
int Num;
char Nom[50];
char Description[100];
float Prix;
} s[10];
int nbp = 0;
void display(struct Produit s[],int p) {
printf("Nom du produit: ");
puts(s[p].Nom);
printf("Description: ");
puts(s[p].Description);
printf("Prix: %.1f", s[p].Prix);
printf("\n");
}
void add(struct Produit s[]);
int searchP(struct Produit s[],char Name[]) {
int found =-1,i;
for (i = 0; i < nbp && found==-1; i++)
{
if (strcmp(s[i].Nom,Name)==0) {
found=i;
}
else
found=-1;
}
return found;
}
int main () {
add(s);
display(s, 0);
return 0;
}
void add(struct Produit s[]){
again:
printf("\nEntrez le nom du produit à ajouter:");
scanf("%s",s[nbp].Nom);
if(searchP(s,s[nbp].Nom)!=-1){
printf("Déjà existant\n");goto again;
}
printf("Entrez la description :");
scanf("%s",s[nbp].Description);
printf("Entrez le prix :");
scanf("%f",&s[nbp].Prix);
nbp++;
}
Execution:
./myprog
Entrez le nom du produit à ajouter:Nom
Entrez la description :Desc
Entrez le prix :1
Nom du produit: Nom
Description: Desc
Prix: 1.0

Is it wrong what I am doing in function "trier" which swaps the name of patient?

The exercise about creating a linked list for patient, then arrange it by their name. I'm trying to swap their name; it seems that what I did doesn't work.
I've tried to take the the previous pointer "prec" and compare the name of next pointer "ptr" then I tried to swap their name in function named "echangedeChaine"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
struct patient{
int cin;
char nom[8];
char prenom[8];
int annee;
struct patient *suivant;
};
struct patient *tete=NULL;
void creationdePatient(){
struct patient* ptr;
char rep;
ptr = malloc(sizeof(struct patient));
tete =ptr;
printf("Saisir Numero de Cin de Nouveau Patient: ");
scanf("%d",&tete->cin);
printf("Saisir Nom de Patient: ");
scanf("%8s",&tete->nom);
printf("Saisir prenom de Patient: ");
scanf("%8s",&tete->prenom);
tete->suivant = NULL;
printf("\nVoulez vous Saisir un autre Patient ?: (O,N): \n");
scanf(" %c",&rep);
while(toupper(rep)=='O'){
ptr = malloc(sizeof(struct patient));
printf("Saisir Numero de Cin de Nouveau Patient: ");
scanf("%d",&ptr->cin);
printf("Saisir Nom de Patient: ");
scanf("%8s",&ptr->nom);
printf("Saisir prenom de Patient: ");
scanf("%8s",&ptr->prenom);
ptr->suivant = tete;
tete=ptr;
printf("\nVoulez vous Saisir un autre Patient ?: (O,N): \n");
scanf(" %c",&rep);
}
}
void echangedeChaine(char x[8] , char y[8]){
char temp[8];
strcpy(temp,y);
strcpy(y,x);
strcpy(x,temp);
}
void printtList(){
struct patient *temp = tete;
while(temp!=NULL){
printf("Cin: %d | Nom:%s | Prenom: %s\n", temp->cin, temp->nom, temp->prenom);
temp=temp->suivant;
}
}
void trier(){
struct patient *ptr = tete;
struct patient*prec;
int echange=0;
do{
while(ptr!=NULL){
prec=ptr;
ptr=ptr->suivant;
if(strcmp(prec->nom,ptr->nom)<0){
echangedeChaine(prec->nom,ptr->nom);
echange=1;
}
}
}while(echange==1);
}
int main()
{
creationdePatient();
printtList();
trier();
printtList();
}
It seems it doesn't work after I tried to execute it.
The are several issues with your code, including (but not necessarily limited to):
Your code in trier() will dereference a NULL pointer at the last element - since its suivant is NULL, and you're doing:
ptr = ptr->suivant;
if(strcmp(prec->nom,ptr->nom) < 0) { ... }
I think you're trying to sort in the wrong order: When strcmp(prec->nom,ptr->nom) is negative, that means the first patient's name is lexicographically earlier than the following patient name - in which case they should not be exchanged.
PS - for those not fluent in French, here's a little glossary for OP's program...
tete = head
suivant = next
nom = last/family name
prenom = first/given name
echange = change (or replace)
chaine = list (or cain)

Issue with function that stopped my program

I have to do create a tree to register some passengers in it (from a plane flight) and then i will search them by their first letter.
My issue is that insert and print function work very well, but the search function do well for first time but when I want to do some other thing after in the main, it doesn't run the other function or things
(I tried to ask the user a letter, then use the function on research (works well here) but then for a second time to ask an other letter to user, and it prints "first letter of the person you are looking for" but i can't write the letter and it does not launch the function after this. so it stop the program there
int i;
char c;
typedef struct Passager
{
char nom[20];
char prenom[20];
int age;
int num_siege;
} Passager;
Passager liste_passagers[30]; //30 = nombre de passagers
typedef struct Arbre
{
Passager value;
struct Arbre *fils_gauche;
struct Arbre *fils_droit;
struct Arbre *racine;
} Arbre;
Arbre *const empty = NULL;
Arbre *passengers = empty; //passengers = arbre des passagers
/*--------------------------------------------*/
void liste_lettre_nom(Arbre *tree, char a)
{
Arbre *temp;
temp = tree;
if (!temp)
{
return;
}
else
{
if (a < temp->value.nom[0])
{
liste_lettre_nom(temp->fils_gauche, a);
}
if (a > temp->value.nom[0])
{
liste_lettre_nom(temp->fils_droit, a);
}
if (a == temp->value.nom[0])
{
printf("passager : \n");
print_passager(temp->value);
liste_lettre_nom(temp->fils_gauche, a);
liste_lettre_nom(temp->fils_droit, a);
}
}
}
/*--------------------------------------------*/
int main()
{
FILE* fichier = NULL;
fichier = fopen("/Users/Patoch/Desktop/Patoch /UNI/Informatique/info sem 2/Structure de données/Labo/TP3/Passager2.txt", "r");
if (fichier == NULL)
{ //test de la bonne ouverture du fichiers
printf("Impossible d'ouvrir le fichier Passagers.docx");
exit(EXIT_FAILURE);
}
for (i=0; i<(sizeof(liste_passagers)/sizeof(liste_passagers[0])); i++)
{
fscanf(fichier, "%s %s %d %d", liste_passagers[i].nom, liste_passagers[i].prenom, &liste_passagers[i].age, &liste_passagers[i].num_siege);
}
passengers = insertion(passengers, liste_passagers[1]);
passengers = insertion(passengers, liste_passagers[2]);
passengers = insertion(passengers, liste_passagers[0]);
passengers = insertion(passengers, liste_passagers[5]);
passengers = insertion(passengers, liste_passagers[26]);
print_arbre(passengers);
printf("-----------------------------\n");
printf("1ere lettre du nom de la personne recherchée: \n");
scanf("%c", &c);
liste_lettre_nom(passengers, c);
printf("-----------------------------\n");
printf("1ere lettre du nom de la personne recherchée: \n");
scanf(" %c", &c);
liste_lettre_nom(passengers, c);
destroy(passengers);
fclose(fichier);
return 0;
}

C program gets an invalid conversion in a function

I have few error commented after this text, i don't get what the compiler is trying to say me, the last function is in to do list i hope that's not the problem, the problem is i want to ask the user for 2 chars after that its send to a function who will compare the strings as a password and a login if the strings are the same, the program continues.
\\initializing argument 1 of int consultar(char, char)\\
\\invalid conversion from char*' to `char' \\
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void introducir_datos (struct agenda cliente[30]);
void mostrar_datos(struct agenda cliente[30]);
char consultar(char login,char password);
struct agenda{
char nombre[10];
char apellido[10];
int edad;
char direccion[20];
int codigo_postal;
};
int main(void)
{
struct agenda cliente[30];
int menu;
char con[3],login[8], password[8];
puts("\n=== Hola bienvenido a nuestra agenda en C ===\n");
puts("Login:");
gets(login);
puts("Password:");
gets(password);
**consultar(login, password);**
while ( menu != 3){
puts("\nQue quieres hacer?\n");
puts("[1]Insertar datos\n[2]Mostrar datos\n[3]Salir del programa\n");
scanf("%d", &menu);
switch(menu){
case 1:
introducir_datos(cliente);
break;
case 2:
mostrar_datos(cliente);
break;
default:
system("cls");
puts("~~~ Opcion incorrecta ~~~");
}
}
}
void introducir_datos (struct agenda cliente[30]){
int x = 0;
puts("\n=== Bienvenido a la introduccion de datos ===\n");
fflush(stdin);
system("pause");
system("cls");
puts("\nDime el nombre:\n");
fflush(stdin);
gets(cliente[x].nombre);
puts("\nDime el apellido:\n");
fflush(stdin);
gets(cliente[x].apellido);
puts("\nDime la edad:\n");
fflush(stdin);
scanf("%d",&cliente[x].edad);
puts("\nDime la direccion:\n");
fflush(stdin);
gets(cliente[x].direccion);
puts("\nDime el codigo postal:\n");
fflush(stdin);
scanf("%d",&cliente[x].codigo_postal);
x++;
}
void mostrar_datos(struct agenda cliente[30]){
for(int i=0;i<20;i++){
int x = 0;
printf("El nombre: %s \nEl apellido: %s\nEl edad: %d\nEl direccion: %s\nEl codigo postal: %d\n", cliente[x].nombre,cliente[x].apellido,cliente[x].edad,cliente[x].direccion,cliente[x].codigo_postal);
}
}
int consultar(char login, char password){
}
You need to change the consultar function (definition and implementation):
int consultar(char login, char password)
to:
int consultar(char *login, char *password)
If you use (char login, char password), it's looking for a single character. Since, by calling it with consultar(login, password);, you're using pointers to char arrays (simplified explaination), you're getting the error.
EDIT As pointed out by user "Namfuak", you should decide whether the function returns a char or an int, and have both definition and implementation be consistent.

Resources