Issue: I am writing this program which allows users to enter their name and school details via fgets() method in a void function after being called from the int function, how do i make sure that the array in this void function is a global array which then allows me to call another function called list users that lists all the user details?
int main(){
int choice, userEnd =1;
printf("1: list user details\n");
printf("2: add user details \n");
printf("3: end the programme\n");
while(userEnd)
{
printf("Enter your choice: \n");
scanf("%d",&choice);
if(choice==1){
listUsers();
}
if(choice ==2){
addUsers();
}
if(choice ==3){
userEnd =0;
}
}
return 0;
}
void addUsers(){
int length = 100;
char userName[length];
char className[length];
printf("Enter user name\n");
fgets(userName,size,stdin);
printf("Enter className:\n");
fgets(className,size,stdin);
printf("User added\n");
}
void listUsers(){
/*if addUsers array is empty, print "empty", else print all user details from addUsers.*/
printf("your name is %s, your class is %s",userName, userSize)
}
CodePudding user response:
If you want to declare a global array, you have to declare it outside the functions scope, so in your case:
/* global array, declared in the global scope */
array_type array[ELEMENTS];
int main () {
}
void addUsers () {
}
void listUsers () {
}
Using that setup you will be able to manipulate the array from every function.
But, as it has been said in the comments, you should not use global variables/arrays in this case. Instead, you should use return values and arguments.
CodePudding user response:
Something like that will do! Note that this code is still a non- working copy of what you want to do but with a few little touches, it should work fine.
/* Global vars */
const int length = 100;
char *userName[length]; // array of strings
char *className[length];
/* Keep track of number of users */
int userCount = 0;
int main(){
int choice, userEnd =1;
printf("1: list user details\n");
printf("2: add user details \n");
printf("3: end the programme\n");
while(userEnd)
{
printf("Enter your choice: \n");
scanf("%d",&choice);
if(choice==1){
listUsers();
}
if(choice ==2){
addUsers();
userCount ;
}
if(choice ==3){
userEnd =0;
}
}
return 0;
}
void addUsers(){
// TODO: make sure userCount doesn't exceed the length
// TODO: define size
printf("Enter user name\n");
fgets(userName[userCount],size,stdin);
printf("Enter className:\n");
fgets(className[userCount],size,stdin);
printf("User added\n");
}
void listUsers(){
int i;
/*if addUsers array is empty, print "empty", else print all user details from addUsers.*/
if (userCount > 0)
{
for (i = 0, i < userCount, i )
{
printf("your name is %s, your class is %s",userName[i], className[i]);
}
}
else
{
printf("No users registered");
}
}