This is my code:
typedef struct person
{
char firstName[40];
char lastName[40];
char id[40];
} Person;
struct personDataBase
{
Person personList[100];
int numOfPersons;
} personDataBase;
Person createPerson()
{
Person p;
printf("Please enter your first name:\n");
gets(p.firstName);
printf("Please enter your last name:\n");
gets(p.lastName);
printf("Please enter your ID number:\n");
gets(p.id);
for (int i = 0; i < 100; i++)
{
while (strcmp(p.id, personDataBase.personList[i].id) == 0)
{
printf("ID already registered in the system, please enter ID correctly:\n");
gets(p.id);
}
}
return p;
printf("** Client registered successfully **\n");
}
void addPerson()
{
personDataBase.personList[personDataBase.numOfPersons] = createPerson();
personDataBase.numOfPersons++;
printf("** New person added to the system **\n");
}
int main()
{
addPerson();
puts(personDataBase.personList[personDataBase.numOfPersons].firstName);
puts(personDataBase.personList[personDataBase.numOfPersons].lastName);
puts(personDataBase.personList[personDataBase.numOfPersons].id);
return 0;
}
When I try to print the person's details and it just prints out BLANK code.
Output:
Please enter your first name:
John
Please enter your last name:
Smith
Please enter your ID number:
12312314
** New person added to the system **
//End of the code (the prompt) -- >
I don't know why it prints out blank instead of the person's values
I tried to type: puts(personDataBase.personList[ 0 ].id);
instead and it is working , but I want to use the code in the main.
The function addPerson
void addPerson()
{
personDataBase.personList[personDataBase.numOfPersons] = createPerson();
personDataBase.numOfPersons++;
printf("** New person added to the system **\n");
}
increases the data member numOfPersons
:
personDataBase.numOfPersons++;
So to output the last added person you need to use the expression personDataBase.numOfPersons - 1
as an index.
That is in main you can write for example
int main( void )
{
addPerson();
for ( int i = 0; i < personDataBase.numOfPersons; i++ )
{
puts(personDataBase.personList[i].firstName);
puts(personDataBase.personList[i].lastName);
puts(personDataBase.personList[i].id);
}
return 0;
}
Pay attention to that the function gets
is unsafe and is not supported by the C Standard. Instead use the function fgets
.
Also it is not a good idea to use file scope variables and when functions depend on file scope variables. You should avoid such a design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.