First of all, im a begginer C programmer, studying in a university. I need to do a program that is kinda like a data base. Thus far i have made the function to input new data, it works, but compiler shows a few warning and notes, i tried a lot of things, but nothing helped. Here is the code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct subjects{
char *subjName[100];
char *lectName[100];
char *lectSurname[100];
double credits;
double studentnum;
}subj;
char subjectname[][100];
char lecturername[][100];
char lecturersurname[][100];
int credits[100];
int students[100];
int newentry=0;
void listInput();
void listEdit();
void listDelete();
void listPrint();
int userChoice();
int main() {
int select;
int r=1;
while(r!=0){
select=userChoice();
switch(select){
case 1:
listPrint();
break;
case 2:
listInput();
break;
case 3:
listDelete();
break;
case 4:
listEdit();
break;
case 0:
r=0;
break;
}
}
return 0;
}
int userChoice(){
int choice,input=0,check;
printf("(1). View all the data\n");
printf("(2). Enter new data\n");
printf("(3). Delete data\n");
printf("(4). Edit data\n");
printf("(0). Exit\n");
printf("-----------------------------\n");
while(input!=1){
printf("Enter your choice\n");
scanf("%d", &choice);
if(choice>4 || choice<0){
printf("Invalid input \n");
}
else
input = 1;
}
return choice;
}
void listPrint(){
for(int i=0; i<newentry; i++){
printf("%d, %s, %s, %s, %d, %d\n",i+1, subjectname[i], lecturername[i], lecturersurname[i], credits[i], students[i]);
}
}
void listInput(){
int i;
char firstLetter,term;
printf("Enter the name of the subject \n");
while(scanf("%s", &subj.subjName)!=1)
printf("Error, subject name must be a text ");
printf("Enter the name of the lecturer \n");
int valid=0;
while(valid!=1){
while(scanf("%s", &subj.lectName)!=1)
printf("Error, lecturer's' name must be a text ");
firstLetter=*subj.lectName;
if(firstLetter>65 && firstLetter<90 && isalpha(firstLetter)){
valid=1;
}
else
printf("Error, lecturer's name must start with a capital letter, try again \nEnter the name of the lecturer \n");
}
valid=0;
printf("Enter the surname of the lecturer\n");
while(valid!=1){
while(scanf("%s", &subj.lectSurname)!=1)
printf("Error, lecturer's surname must be a text ");
firstLetter=*subj.lectSurname;
if(firstLetter>65 && firstLetter<90 && isalpha(firstLetter)){
valid=1;
}
else
printf("Lecturer's surname must start with a capital letter, try again \nEnter the surname of the lecturer \n");
}
printf("Enter the amount of credits in course \n");
while(1){
scanf("%lf", &subj.credits);
if(subj.credits<0 || subj.credits != (int)subj.credits)
printf("Error, amount of credits must be a positive integer, try again \n");
if(subj.credits>0 && subj.credits == (int)subj.credits)
break;
}
printf("Enter the number of students \n");
while(1){
scanf("%lf", &subj.studentnum);
if(subj.studentnum<0 || subj.studentnum != (int)subj.studentnum)
printf("Error, number of students must be a positive integer,try again \n");
if(subj.studentnum>0 && subj.studentnum == (int)subj.studentnum)
break;
}
printf("Added a new entry.\n\n");
strncpy(subjectname[newentry], subj.subjName, 99);
strncpy(lecturername[newentry], subj.lectName, 99);
strncpy(lecturersurname[newentry], subj.lectSurname, 99);
credits[newentry]=subj.credits;
students[newentry]=subj.studentnum;
newentry++;
}
void listDelete(){
printf("33333333333");
}
void listEdit(){
printf("4444444");
}
And the warnings:
In function 'listInput':
96 14 [Warning] assignment makes integer from pointer without a cast
108 14 [Warning] assignment makes integer from pointer without a cast
132 33 [Warning] passing argument 2 of 'strncpy' from incompatible pointer type
79 9 [Note] expected 'const char * restrict' but argument is of type 'char **'
133 34 [Warning] passing argument 2 of 'strncpy' from incompatible pointer type
79 9 [Note] expected 'const char * restrict' but argument is of type 'char **'
134 37 [Warning] passing argument 2 of 'strncpy' from incompatible pointer type
79 9 [Note] expected 'const char * restrict' but argument is of type 'char **
At top level:
14 6 [Warning] array 'subjectname' assumed to have one element
15 6 [Warning] array 'lecturername' assumed to have one element
16 6 [Warning] array 'lecturersurname' assumed to have one element
What can i do to fix those warnings? The program works just fine, but i cant pass if i dont fix the warnings.
Here is a better way to do things
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char *subjName;
char *lectName;
char *lectSurname;
double credits;
double num_students;
}Subject;
typedef struct{
Subject **subjs;
int num_subjs;
}Subjects;
void listInput();
void listEdit();
void listDelete();
void listPrint();
int userChoice();
int main() {
Subjects *subjects = malloc(sizeof(Subjects));
subjects->num_subjs = 0;
subjects->subjs = NULL;
int r=1;
while(r!=0){
int select=userChoice();
switch(select){
case 1:
listPrint(subjects);
break;
case 2:
listInput(&subjects);
break;
case 3:
listDelete();
break;
case 4:
listEdit();
break;
case 0:
r=0;
break;
}
}
return 0;
}
int userChoice(){
int choice,input=0,check;
printf("(1). View all the data\n");
printf("(2). Enter new data\n");
printf("(3). Delete data\n");
printf("(4). Edit data\n");
printf("(0). Exit\n");
printf("-----------------------------\n");
while(input!=1){
printf("Enter your choice\n");
scanf("%d", &choice);
if(choice>4 || choice<0){
printf("Invalid input \n");
}
else
input = 1;
}
return choice;
}
void listPrint(Subjects *subjects){
for(int i=0; i< subjects->num_subjs; i++){
printf("%d, %s, %s, %s, %d, %d\n",i+1, subjects->subjs[i]->subjName, subjects->subjs[i]->lectName, subjects->subjs[i]->lectSurname, subjects->subjs[i]->credits, subjects->subjs[i]->num_students);
}
}
char *getln()
{
char *line = NULL, *tmp = NULL;
size_t size = 0, index = 0;
int ch = 1;
while (ch) {
ch = getc(stdin);
if (ch == '\n')
ch = 0;
if (size <= index) {
size += 1;
tmp = realloc(line, size);
if (!tmp) {
free(line);
line = NULL;
break;
}
line = tmp;
}
line[index++] = ch;
}
return line;
}
int isText(char *str,char *name){
for(int i = 0; i < strlen(str);i++){
if((str[i]<'A' || str[i]>'z') && str[i]!=' '){
printf("Error, %s must be a text \n",name);
return 0;
}
}
return 1;
}
int isNegative(int n){
if(n < 0){
printf("Error, number of students must be a positive integer,try again \n");
return 1;
}
return 0;
}
void listInput(Subjects **p_subjects){
while ( getchar() != '\n' );
Subject *new_subj = malloc(sizeof(Subject));
new_subj->subjName = NULL;
new_subj->lectName = NULL;
new_subj->lectSurname = NULL;
new_subj->credits = 0;
new_subj->num_students = 0;
do{
printf("Enter the name of the subject \n");
new_subj->subjName = getln();
}while(!isText(new_subj->subjName,"Subject name"));
do{
printf("Enter the name of the lecturer \n");
new_subj->lectName = getln();
}while(!isText(new_subj->lectName,"Lecturer's name"));
do{
printf("Enter the surname of the lecturer\n");
new_subj->lectSurname = getln();
//Convert to uppercase
new_subj->lectSurname[0] &= '_';
}while(!isText(new_subj->lectSurname,"Lecturer's surname"));
do{
printf("Enter the number of credits \n");
scanf("%d", &new_subj->credits);
}while(isNegative(new_subj->num_students));
do{
printf("Enter the number of students \n");
scanf("%d", &new_subj->num_students);
}while(isNegative(new_subj->num_students));
(*p_subjects)->subjs = realloc((*p_subjects)->subjs,sizeof(Subject*)*(++(*p_subjects)->num_subjs));
(*p_subjects)->subjs[(*p_subjects)->num_subjs-1] = new_subj;
printf("Added a new entry.\n\n");
}
void listDelete(){
printf("33333333333");
}
void listEdit(){
printf("4444444");
}
Related
I'm trying to create a program that allows users to add information into a nameCard array using a function called AddNameCard. but when I try to add another set of input in, the previous items seems to get overwritten. and the listnamecard function only displays the last inputted items. Anyone know what i need to do to get around this problem? I'm learning C programming currently, go easy on me please :).
#include <stdio.h>
#include <stdlib.h>
# define Max_Size 5
typedef struct
{
int nameCardID;
char personName[20];
char companyName[20];
} NameCard;
NameCard nameCard[Max_Size];
void AddNameCard() {
int j;
printf("\n");
for (int i = j - 1; i < j; i++){
printf("Enter Name Card ID: \n");
scanf("%d", &nameCard[i].nameCardID);
printf("Enter Person Name: \n");
scanf("%s", &nameCard[i].personName);
printf("Enter Company Name : \n");
scanf("%s", &nameCard[i].companyName);
}
printf("\n");
return;
}
void ListNameCard() {
int j;
printf("\n");
printf("\nName_Card_ID Person_Name Company_Name \n");
for (int i = 0; i < j; i++){
printf("%d %s %s \n", nameCard[i].nameCardID, nameCard[i].personName, nameCard[i].companyName);
}
printf("\n");
return;
}
void GetNameCard() {
printf("%d %s %s", nameCard[1].nameCardID, nameCard[1].personName, nameCard[1].companyName);
}
int main()
{
int options;
while (options != 5) {
printf("1:List Name Cards\n2:Add Name Card\n3:Remove Name Cards\n4:Get Name Cards\n5:quit\n");
printf("\n");
printf("What would you like to do? : ");
scanf("%d", &options);
switch (options)
{
case 1:
ListNameCard();
break;
case 2:
AddNameCard();
break;
case 3:
printf("Case3 ");
printf("\n");
break;
case 4:
GetNameCard();
break;
default:
printf("quit ");
}
}
#include <stdio.h>
#include <stdlib.h>
#define Max_Size 5
typedef struct {
int nameCardID;
char personName[20];
char companyName[20];
}
NameCard;
NameCard nameCard[Max_Size];
void AddNameCard() {
printf("\n");
int i;
printf("enter the number of person you want to add :");
scanf("%d", & i);
printf("Enter Name Card ID: \n");
scanf("%d", & nameCard[i - 1].nameCardID);
printf("Enter Person Name: \n");
scanf("%s", nameCard[i - 1].personName);
printf("Enter Company Name : \n");
scanf("%s", nameCard[i - 1].companyName);
printf("\n");
return;
}
void ListNameCard() {
printf("\n");
printf("\nName_Card_ID Person_Name Company_Name \n");
for (int i = 0; i < Max_Size; i++) {
printf("%d %s %s \n", nameCard[i].nameCardID, nameCard[i].personName, nameCard[i].companyName);
}
printf("\n");
return;
}
void GetNameCard() {
int n;
printf("\n");
printf("enter the number of the person");
scanf("%d", & n);
printf("%d %s %s", nameCard[n - 1].nameCardID, nameCard[n - 1].personName, nameCard[n - 1].companyName);
printf("\n");
}
int main() {
int options;
while (options != 5) {
printf("1:List Name Cards\n2:Add Name Card\n3:Remove Name Cards\n4:Get Name Cards\n5:quit\n");
printf("\n");
printf("What would you like to do? : ");
scanf("%d", & options);
switch (options) {
case 1:
ListNameCard();
break;
case 2:
AddNameCard();
break;
case 3:
printf("Case3 ");
printf("\n");
break;
case 4:
GetNameCard();
break;
default:
printf("quit ");
}
}
}
Let's follow the comments' suggestions.
First we avoid using options variable uninitialized by changing:
while (options != 5) {
...
}
To:
do {
... (set options variable here)
} while (options != 5);
Secondly, we change the name of j variable to count and use it as function parameter/return so we keep track and update the number of added cards. For instance, AddNameCard becomes:
int AddNameCard(int count)
{
if (count < Max_Size) {
count++;
int i = count - 1;
printf("\n");
printf("Enter Name Card ID: ");
scanf("%d", &nameCard[i].nameCardID);
discard_newline();
printf("Enter Person Name: ");
scanf("%19[^\n]", nameCard[i].personName);
discard_newline();
printf("Enter Company Name: ");
scanf("%19[^\n]", nameCard[i].companyName);
discard_newline();
} else {
printf("Maximum number of cards reached\n");
}
printf("\n");
return count;
}
(discard_newline prevents newline characters to creep into the next scanf. "%19[^\n]" format prevents buffer overrun into 20 length strings.)
The name of an array variable is already taken as its address (or the address of its first element). So personName and companyName members shouldn't be preceded by &.
The code becomes:
#include <stdio.h>
#include <stdlib.h>
#define Max_Size 5
typedef struct
{
int nameCardID;
char personName[20];
char companyName[20];
} NameCard;
NameCard nameCard[Max_Size];
void discard_newline(void)
{
while( getchar() != '\n' );
}
int AddNameCard(int count)
{
if (count < Max_Size) {
count++;
int i = count - 1;
printf("\n");
printf("Enter Name Card ID: ");
scanf("%d", &nameCard[i].nameCardID);
discard_newline();
printf("Enter Person Name: ");
scanf("%19[^\n]", nameCard[i].personName);
discard_newline();
printf("Enter Company Name: ");
scanf("%19[^\n]", nameCard[i].companyName);
discard_newline();
} else {
printf("Maximum number of cards reached\n");
}
printf("\n");
return count;
}
void ListNameCard(int count) {
if (count > 0) {
printf("\nName_Card_ID Person_Name Company_Name\n");
for (int i = 0; i < count; i++){
printf("%d %s %s \n", nameCard[i].nameCardID, nameCard[i].personName, nameCard[i].companyName);
}
} else {
printf("Empty list: none added yet\n");
}
printf("\n");
return;
}
void GetNameCard() {
printf("%d %s %s", nameCard[1].nameCardID, nameCard[1].personName, nameCard[1].companyName);
}
int main()
{
int options;
int count = 0;
do {
printf("1:List Name Cards\n2:Add Name Card\n3:Remove Name Cards\n4:Get Name Cards\n5:quit\n");
printf("\n");
printf("What would you like to do? : ");
scanf("%d", &options);
switch (options)
{
case 1:
ListNameCard(count);
break;
case 2:
count = AddNameCard(count);
break;
case 3:
printf("Case3 ");
printf("\n");
break;
case 4:
GetNameCard();
break;
default:
printf("quit\n");
}
} while (options != 5);
}
Running it:
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 1
Empty list: none added yet
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 2
Enter Name Card ID: 123
Enter Person Name: John Smith
Enter Company Name: COMP_01
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 1
Name_Card_ID Person_Name Company_Name
123 John Smith COMP_01
1:List Name Cards
2:Add Name Card
3:Remove Name Cards
4:Get Name Cards
5:quit
What would you like to do? : 5
quit
You still have to complete the other options.
I try to give my Void function a struct but when I do this I get a errors.
first:error: subscript of pointer to incomplete type 'struct Lager'.
and a warning:warning: incompatible pointer types passing 'Lager (*)[200]' to parameter of type 'struct Lager *' [-Wincompatible-pointer-types].
and
warning: declaration of 'struct Lager' will not be visible outside of this function [-Wvisibility].
I already asked my fellow students but no-one of them could help me.
void case1(struct Lager *wh, int l){
int end;
int v;
char ques;
do {
printf("\nEnter the product name: ");
scanf("%s", *(wh[l]).artikel);
printf("\nAmount of products: ");
scanf("%i", &*(wh[l]).anzahl);
printf("\n\nAdd another product ? (Y/N)");
// add a space before % to skip leading whitespace
scanf(" %c", &ques);
switch (ques) {
case 'Y':
v++;
l++;
break;
case 'N':
end = 1;
v = 0;
l++;
break;
default:
printf("Wrong entry\n");
end = 1;
break;
}
} while (end != 1);
if (v >= 2) {
printf("Product added successfully\n\n");
}else {
printf("Products have been successfully added\n\n");
}
}
int main() {
typedef int item;
typedef char max;
typedef int GanzvieleBuchstaben;
//unien wär die bessere variante (eigentlich). weil platzsparender
typedef struct managementtool
{
max artikel[200];
item anzahl;
}Lager;
Lager lager[200];
printf("Welcome to Warehouse Management 97\n\n\nWhat do you want to do ?\n");
GanzvieleBuchstaben a,l,f,i,v,x,p,c,я,и,ii;
int exit, end, all;
int b = 201;
char ques, nu1;
char find [100];
do {
printf("\n(1)Add article\n(2)Edit article.\n(3)Search entry.\n(4)Show stock.\n(5)Exit\n");
scanf("%i",&x);
switch (x) {
case 1://add
case1(&lager, l);
*Irrelevant stuff down there*
I am writing a program to print a fee invoice of a student. When I call my function getPrefix() my program essentially crashes and says Process returned -1073741819; the program compiles and everything.
The problem is occuring in my deleteCourse() function. I call the function getPrefix() to print out the name associated with the specific crn and the program crashes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LOAD 12
#define creditHour 120.25
// prototype functions above main
void printMenu();
void addCourse(int [], int crnValid[]);
void courseList ();
int deleteCourse (int [], int crnValid[]);
char* getPrefix (int);
void printInvoice (int [], int);
int main()
{ // start main
int studentId ;
int option = 1;
int crn[MAX_LOAD] = {0}; // used to keep track of courses being taken
int crnValid[MAX_LOAD] = {4587,4599,8997,9696,7895,9658,4287,9599,8927,7696,7890,9008} ; // used to check if crns are valid
printf("Welcome! Enter the student's ID number:\n");
scanf("%d", &studentId);
while (option != 0){
printMenu();
scanf("%d", &option);
switch(option){
case 1:
addCourse (crn, crnValid);
break;
case 2:
deleteCourse (crn, crnValid);
break;
case 3:
printInvoice (crn, studentId) ;
break;
case 0:
break;
default:
printf("Please enter a valid option: \n");
} ;
}
return 0;
} // end main
// define functions below main
// ------------------------------------------------------------------------------------
void printMenu(){
printf("\n---------------------------------\n") ;
printf("Choose from the following options:\n");
printf("1- Add a course for the student\n");
printf("2- Drop a course for the student\n");
printf("3- Print the fee invoice\n");
printf("0- Exit program\n");
printf("---------------------------------\n") ;
printf("Enter your selection: ");
}
// --------------------------------------------------------------------------------------
void addCourse(int crn[], int crnValid[]){
char choice ;
printf("Would you like to print the list of courses? (y/n)");
scanf(" %c", &choice) ;
if (choice == 'y'){
courseList();
}
int i; // loop incrementer
int success = 0;
int valid;
for (i = 1; i < MAX_LOAD; i++){
if (crn[i] == 0){
printf("Enter the course number to add: ");
scanf("%d", &crn[i]);
success = 1; // success = 1 when course has not been taken
break ;
}
}
if (success == 0){
printf("Course can't be added, you have attained the max number of courses!\n");
}
else {
printf("Course added, you have added course %d\n", crn[i]) ;
}
}
// --------------------------------------------------------------------------------------
void courseList ()
{
printf("CRN\tCOURSE\t\tCREDIT HOURS\n");
printf("4587\tMAT 236\t\t4\n");
printf("4599\tCOP 220\t\t3\n");
printf("8997\tGOL 124\t\t1\n");
printf("9696\tCOP 100\t\t3\n");
printf("7895\tMNT 125\t\t2\n");
printf("9658\tOPT 120\t\t3\n");
printf("4287\tMAT 836\t\t4\n");
printf("9599\tCOP 220\t\t3\n");
printf("8927\tGOM 124\t\t3\n");
printf("7696\tCOT 100\t\t4\n");
printf("7890\tMOT 125\t\t3\n");
printf("9008\tOPT 520\t\t5\n");
}
// -------------------------------------------------------------------------------------
int deleteCourse(int crn[], int crnValid[])
{
int i;
int success = 0;
int crnToDelete;
printf("Enter the course number to delete: ");
scanf("%d", &crnToDelete);
char prefix[20] ;
for (i=1; i < MAX_LOAD; i++){
if ( crn[i] == crnToDelete )
{
crn[i] = 0; // deletes course from array crn
success = 1;
break;
}
}
if (success == 0){
printf("The student isn't taking %d/%s", crnToDelete, getPrefix(crnToDelete)) ;
}
else {
printf("Course deleted!\n");
}
return crnToDelete ;
}
//--------------------------------------------------------------------------------------
char* getPrefix (int crnToDelete){
switch(crnToDelete){
case 4587:
return "MAT 236";
case 4599:
return "COP 220";
case 8997:
return "GOL 124";
case 9696:
return "COP 100";
case 4580:
return "MAT 230";
case 4581:
return "MAT 231";
case 4582:
return "MAT 232";
case 4583:
return "MAT 233";
case 3587:
return "MAT 256";
case 4519:
return "COP 420";
case 6997:
return "GOL 127";
case 9494:
return "COP 101";
}
}
// --------------------------------------------------------------------------------------
void printInvoice (int crn [], int studentId)
{
printf("\n\tVALENCIA COMMUNITY COLLEGE\n");
printf("\tORLANDO FL 10101\n");
printf("\t----------------------------\n");
printf("\n\tFee Invoice Prepared for Student V%d\n", studentId);
printf("\n\t1 Credit Hour = $ 120.25\n");
printf("\n\tCRN\tCR_PREFIX\tCR_HOURS");
int i;
for (i=1; i < MAX_LOAD; i++)
{
if (crn[i] != 0){ // if a course is in spot i, print course
printf("\n\t%d\n", crn[i]) ;
}
}
printf("\n\t\tHealth and Id fees:\t $ 35.00");
printf("\n\t-----------------------------------------");
printf("\n\t\tTotal Payments:") ;
}
#include <stdio.h>
#include <string.h>
#define mL 5
#define NL 20
#define UL 6
struct LIST
{
char n[NL];
float am;
char u[UL];
};
struct array
{
struct LIST array;
};
void addCityInformation(struct array *add, int *items);
void printCities(struct array *all, int items);
int main(void)
{
struct array shopping[mL];
int choice, nrOfItemsAdded = 0;
do
{
printf("\nWhat du you want to do?");
printf("\n1 - add grocery");
printf("\n2 - print shopping list");
printf("\n3 - exit");
printf("\nYour choice: ");
scanf("%d", &choice);
while(getchar() != '\n');
switch (choice)
{
case 1:
addCityInformation(&shopping[nrOfItemsAdded], &nrOfItemsAdded);
break;
case 2:
printCities(shopping, nrOfItemsAdded);
break;
case 3:
printf("Exiting program\n\n");
break;
default:
printf("Invalid input\n\n");
break;
}
}
while(choice != 3);
return 0;
}
int clean_stdin()
{
while (getchar()!='\n');
}
void addCityInformation(struct array *add, int *items)
{
if(*items == mL)
printf("No more space in the list\n");
else
{
printf("Enter name: ");
fgets(add->array.n, NL, stdin);
add->array.n[strlen(add->array.n)-1] = '\0';
do {
printf("Enter amount: ");
}while (scanf("%f", &add->array.am )); //loop untill other than float
getchar();
printf("Enter unit: ");
fgets((add->array.u), UL, stdin);
add->array.u[strlen(add->array.u)-1] = '\0';
(*items)++;
}
}
void printCities(struct array *all, int items)
{
printf("\n\n%-20s %-15s %-9s | %-6s\n", "Name", "amount", "unit");
printf("--------------------------------------------------------\n");
for(int i = 0; i < items; i++)
printf("%-20s %-15.1f %-9.4s \n", all[i].array.n, all[i].array.am, all[i].array.u);
}
This is my loop beside that i am only showing a part of the code. It now just continues to give enter amount and letting me register it in the struct. I want to restrict the user to only entering positive numbers and no character at all. And if he types a character it should rerun the loop even if it is 123Av123 it should run the loop and only register the correct number
Edit: now showing the whole code//loop untill other than float is what i want help with
int check=scanf("%f", &add->array.am )
if(check!=1||add->array.am<0){
printf("Incorrect input");
return 1;
}
I think that will do it.
Edit: you wanted it to rerun after so use continue; instead of return;
The addInfo() adds information into the array of structures and the function printList() outputs all of the elements of that array. But my printList() is outputting only the last element that was added. What can be wrong? Does it add elemets into the array incorrectly?
#include <stdio.h>
#include <stdlib.h>
//structure Location
typedef struct Location{
char locName[35];
char locDesc[85];
float latitude;
float longitude;
} LocationArray;
void addInfo(LocationArray **myArray, int*, int*);
void printList(LocationArray **myArray, int*);
void quitProgram();
void resizeArray(LocationArray **myArray, int*);
//Menu that receives the user input
//and performs corresponding operations based
//on the menu choice
void printMenu(LocationArray **myArray, int *count, int *max){
printf("Hello! Please choose from the menu: \n");
printf("Type 'A' or 'a' for adding additional location to the array\n");
printf("Type 'P' or 'p' for printing the current list of locations\n");
printf("Type 'Q' or 'q' to quit the program\n");
char input = 0;
scanf(" %c", &input);
//Handles the invalid character input
//exits if the character does not correspond
//to the valid menu option
while(input != 'A' && input != 'a'
&& input != 'P' && input != 'p'
&& input != 'Q' && input != 'q'){
printf("Invalid character! Try entering a char again: \n");
scanf(" %c", &input);
}
//Calls other functions
//based on the character input
switch(input){
case 'A':
case 'a':
addInfo(myArray, count, max); //Calls function that adds more locations into the array
break;
case 'P':
case 'p':
printList(myArray, count); //Calls the function that prints the current list of locations
break;
case 'Q':
case 'q':
quitProgram(); //Calls the function that terminates the program
break;
}
}
//Adds info into the array of structures
void addInfo(LocationArray **myArray, int *count, int *numberOfLoc){
if(*count == *numberOfLoc){ // Checks if the array is already full
resizeArray(myArray, numberOfLoc); //Resizes the array if it's full
printf("Please enter the name for the location:\n");
scanf(" %[^\n]", &(*myArray)->locName); //Gets the user input for the Location Name
printf("\nNow enter the description:\n");
scanf(" %[^\n]", &(*myArray)->locDesc); //Gets the user input for the Location Description
printf("\nNow enter the value for the latitude:\n");
scanf("%f", &(*myArray)->latitude); //Gets the user input for the Latitude
printf("\nNow enter the value for the longitude:\n");
scanf("%f", &(*myArray)->longitude); //Gets the user input for the Latitude
(*count)++; //Increment the count
}
else{ //Else, a used fills it out
printf("Please enter the name for the location:\n");
scanf(" %[^\n]", &(*myArray)->locName); //Gets the user input for the Location Name
printf("\nNow enter the description:\n");
scanf(" %[^\n]", &(*myArray)->locDesc); //Gets the user input for the Location Description
printf("\nNow enter the value for the latitude:\n");
scanf("%f", &(*myArray)->latitude); //Gets the user input for the Latitude
printf("\nNow enter the value for the longitude:\n");
scanf("%f", &(*myArray)->longitude); //Gets the user input for the Latitude
(*count)++; //Increment the count
}
}
//Resizes(doubles) the array size if the max limit is achieved
void resizeArray(LocationArray **myArray, int *numberOfLoc){
*numberOfLoc = *numberOfLoc * 2; //Double the size
LocationArray *temp;
temp = (LocationArray*)realloc(*myArray, *numberOfLoc *sizeof(LocationArray)); //Reallocates more memory
//Checks if the memory heap is exhausted
if(temp == NULL){
printf("The memory heap is exhausted!\n");
}
else{
*myArray = temp; //Copy from the temp struct variable to myArray
}
}
//Prints all of the elements of the array
void printList(LocationArray **myArray, int *count){
if((*count) == 0){ //If the list is empty, then return
printf("The list is empty!");
return;
}
int i;
for(i = 0; i < (*count); i++){
printf("Location name: %s\n", (*myArray[i]).locName);
printf("Description: %s\n", (*myArray[i]).locDesc);
printf("Latitude: %f\n", (*myArray[i]).latitude);
printf("Longitude: %f\n", (*myArray[i]).longitude);
}
}
//Quits the program
void quitProgram(){
printf("Bye!");
exit(0);
}
int main()
{
printf("How many locations would you like to be inside the array?\n");
int numberOfLoc = 0; //variable for storing the size of the LocationArray
scanf(" %d", &numberOfLoc); //gets the user input and stores in numerOfLoc
LocationArray *myArray; //declares a LocationArray with the size of numberOfLoc
myArray = (LocationArray*)malloc(numberOfLoc*sizeof(LocationArray));
int count = 0;
while(1){
//Prints the menu
printMenu(&myArray, &count, &numberOfLoc);
}
//Free the pointer
free(myArray);
return 0;
}
In printList, you have the lines
for(i = 0; i < (*count); i++){
printf("Location name: %s\n", (*myArray[i]).locName);
printf("Description: %s\n", (*myArray[i]).locDesc);
printf("Latitude: %f\n", (*myArray[i]).latitude);
printf("Longitude: %f\n", (*myArray[i]).longitude);
}
Use of *myArray[i] is incorrect. That is equivalent to *(myArray[i]). You need to use: (*myArray)[i].
for(i = 0; i < (*count); i++){
printf("Location name: %s\n", (*myArray)[i].locName);
printf("Description: %s\n", (*myArray)[i].locDesc);
printf("Latitude: %f\n", (*myArray)[i].latitude);
printf("Longitude: %f\n", (*myArray)[i].longitude);
}
You can make code in printList simpler by changing the argument to
LocationArray *myArray and int count.
void printList(LocationArray *myArray, int count){
if(count == 0){ //If the list is empty, then return
printf("The list is empty!");
return;
}
int i;
for(i = 0; i < count; i++){
printf("Location name: %s\n", myArray[i].locName);
printf("Description: %s\n", myArray[i].locDesc);
printf("Latitude: %f\n", myArray[i].latitude);
printf("Longitude: %f\n", myArray[i].longitude);
}
}
and make sure to change the call to the function. Instead of
printList(myArray, count);
use
printList(*myArray, *count);
Further cleanup
scanf(" %[^\n]", &(*myArray)->locName);
scanf(" %[^\n]", &(*myArray)->locDesc);
are wrong on two accounts.
You don't need to use &.
You need to use the count-th element of myArray. The above always store the data in the first element of myArray.
use
scanf(" %[^\n]", (*myArray)[*count].locName);
scanf(" %[^\n]", (*myArray)[*count].locDesc);
Modify the other scanf lines also to:
scanf("%f", &(*myArray)[*count].latitude);
scanf("%f", &(*myArray)[*count].longitude);