For some reason when i input my time , description and index and click quit to print the array that i have populated with values and strings, i get a bunch of garbage values printed instead of what i inputed, not sure what im doing wrong. any advice?
For some reason when i input my time , description and index and click quit to print the array that i have populated with values and strings, i get a bunch of garbage values printed instead of what i inputed, not sure what im doing wrong. any advice?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
struct event //data type called event which holds time and description for events
{
int hour; //holds the hour digit between 0-23
int minute; //holds the minute digit between 0-59
char description[41];
//holds the description for the reason of the alarm
};
typedef struct event Event; //allows coder to only have to use "Event" instead of "struct event"
int InputRange(int min, int max);
Event* InputEvent(Event *newEvent);
int AddEventAtIndex(Event list[], Event e, int i);
//int InsertionSortEvent(Event list[], int *p_size, Event e);
//void DisplayEvent(Event e);
//void DisplayEventList(Event list[], int size);
//int DeleteEvent(Event list[], int i, int *p_size);
int main (void)
{
Event EventList[MAX];
Event e;
int i=0;
int eventListSize = 0;
int choice;
do
{
printf("__= Scheduler v1.0 =__\n");
printf("1. Schedule an event.\n");
printf("2. Delete an event.\n");
printf("3. Display schedule.\n");
printf("4. Save schedule.\n");
printf("5. Load schedule.\n");
printf("6. Exit\n");
switch(choice = InputRange(1, 6))
{
case 1: InputEvent( EventList );
i = AddEventAtIndex(EventList, e, i);
break;
/* case 2: pHead = deleteStudent(pHead);
break;
case 3: printf("Press 1 to search by ID or 2 to search by name: \n");
scanf("%d", &search);
if (search == 1){
searchStudentID(pHead);
}
else if (search == 2){
searchStudentlName(pHead);
}
else{
printf("Invalid selection");
}
break;
case 4: displayStudentInfo(pHead);
break;
case 5: saveStudentInfo(pHead);
break;
case 6: end(pHead);
break;*/
default: printf("Exiting Program\n\n");
}
}
while ( choice != 6 );
printf("Index #[]\tTime\tDescription");
for ( int j = 1; j < 6; j++)
{
printf("\n[%d]\n\t%d:%d \t %s", j, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
}
int InputRange(int min, int max)
{
int timenumber;
printf("Please enter a number between %d - %d\n", min, max);
scanf("%d", &timenumber);
printf("\n");
if (timenumber < min || timenumber > max)
{
printf("Invalid Entry\n");
InputRange(min, max);
}
return timenumber;
}
Event* InputEvent(Event *newEvent)
{
if (newEvent != NULL) // quality assurance:
// make sure the pointer is valid
{
printf("Enter the event time:\n");
newEvent->hour = InputRange(0, 23);
newEvent->minute = InputRange(0, 59);
printf("Enter the event description:\n");
fgetc(stdin);
fgets(newEvent->description, 41, stdin);
printf("\n");
}
return newEvent;
}
int AddEventAtIndex(Event list[], Event e, int i)
{
--i;
printf("Where in the array would you like to store this event\n");
i = InputRange(1, 5);
list[i].hour = e.hour;
list[i].minute = e.minute;
strcpy(list[i].description, e.description);
return i;
}
Why does my program keep printing garbage values?
You use non initialized data, in main you have :
Event e;
...
i = AddEventAtIndex(EventList, e, i);
where e is not initialized but used in AddEventAtIndex :
int AddEventAtIndex(Event list[], Event e, int i)
{
...
list[i].hour = e.hour;
list[i].minute = e.minute;
strcpy(list[i].description, e.description);
the behavior of strcpy with an non initialized value is undefined and can have a dramatic consequences.
Probably the call InputEvent( EventList ); must be replaced by InputEvent(&e);
In
for ( int j = 1 ; j < 6 ; j++)
{
printf("\n[%d]\n\t%d:%d \t %s", j, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
You access out of EventList when j is 5 and 6, do for instance :
for ( int j = 0 ; j < MAX ; j++)
{
printf("[%d]\t%d:%d \t %s\n", j+1, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
But you also write entries never set printing 'garbage values', more the fact to print a string non initialized has undefined effect. A way to separate entries set and not set is to initialize all the hours by 24 and to test that value in the loop to write or not the entry.
I also changed the format because the newline after the index is not compatible with printf("Index #[]\tTime\tDescription"); and it is better to put the other newline after all rather than before to flush the output line, so also change printf("Index #[]\tTime\tDescription"); by puts("Index #[]\tTime\tDescription");
MAX is not a very good name because it is more a SUP, or just rename it by SIZE
In main you do not use eventListSize
In AddEventAtIndex
--i must be done after i = InputRange(1, 5); or just do i = InputRange(1, 5) - 1; else when i values 5 list[i] is out of list so you write out of list with an undefined behavior.
So finally the parameter i is useless, remove it.
The return index is also not used in main, you use it to assign i and do not used the value of i after. AddEventAtIndex do not need to return a value.
In InputRange
You do not check the result of scanf so the value of timenumber is undefined if a non valid integer was enter and if you do not purge the input so all the next scanf to get a number will not success
Also if the value is not in the range you just call InputRange(min, max); without returning its value so you finally return the invalid value, put all in a for(;;) for instance to only return when the value is correct.
You use fgets in InputEvent, to mix it with scanf to read number is a source of problem, replace the scanf by the use of fgets then a sscanf on the read line
In InputEvent
When you do fgetc(stdin); you probably hope to bypass a newline but if the user enter characters after the number in InputRange (supposing a number was enter) fgets will read the first of them and fgets will not get the expected description. The solution is to do fgets then sscanf in InputRange as I said above allowing you to remove that fgetc
A proposal taking into account my remarks :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 5
struct event //data type called event which holds time and description for events
{
int hour; //holds the hour digit between 0-23
int minute; //holds the minute digit between 0-59
char description[41]; //holds the description for the reason of the alarm
};
typedef struct event Event; //allows coder to only have to use "Event" instead of "struct event"
int InputRange(int min, int max);
Event* InputEvent(Event *newEvent);
void AddEventAtIndex(Event list[], Event e);
//int InsertionSortEvent(Event list[], int *p_size, Event e);
//void DisplayEvent(Event e);
//void DisplayEventList(Event list[], int size);
//int DeleteEvent(Event list[], int i, int *p_size);
int main (void)
{
Event EventList[MAX];
Event e;
int choice;
/* mark uset entries */
for (int i = 0; i != MAX; ++i)
EventList[i].hour = 24;
do
{
printf("__= Scheduler v1.0 =__\n");
printf("1. Schedule an event.\n");
printf("2. Delete an event.\n");
printf("3. Display schedule.\n");
printf("4. Save schedule.\n");
printf("5. Load schedule.\n");
printf("6. Exit\n");
switch(choice = InputRange(1, 6))
{
case 1:
InputEvent( &e );
AddEventAtIndex(EventList, e);
break;
/*case 2: pHead = deleteStudent(pHead);
break;
case 3: printf("Press 1 to search by ID or 2 to search by name: \n");
scanf("%d", &search);
if (search == 1){
searchStudentID(pHead);
}
else if (search == 2){
searchStudentlName(pHead);
}
else{
printf("Invalid selection");
}
break;
case 4: displayStudentInfo(pHead);
break;
case 5: saveStudentInfo(pHead);
break;
case 6: end(pHead);
break;*/
default: printf("Exiting Program\n\n");
}
}
while ( choice != 6 );
puts("Index #[]\tTime\tDescription");
for ( int j = 0 ; j < MAX ; j++)
{
if (EventList[j].hour != 24)
printf("\t[%d]\t%d:%d \t %s\n", j+1, EventList[j].hour,
EventList[j].minute, EventList[j].description);
}
}
int InputRange(int min, int max)
{
char line[32];
int timenumber;
for (;;) {
printf("Please enter a number between %d - %d\n", min, max);
if (fgets(line, sizeof(line), stdin) == NULL)
/* EOF */
exit(-1);
if ((sscanf(line, "%d", &timenumber) == 1) &&
(timenumber >= min) &&
(timenumber <= max))
return timenumber;
printf("Invalid Entry\n");
}
}
Event* InputEvent(Event *newEvent)
{
if (newEvent != NULL) // quality assurance:
// make sure the pointer is valid
{
printf("Enter the event time:\n");
newEvent->hour = InputRange(0, 23);
newEvent->minute = InputRange(0, 59);
printf("Enter the event description:\n");
fgets(newEvent->description, sizeof(newEvent->description), stdin);
printf("\n");
}
return newEvent;
}
void AddEventAtIndex(Event list[], Event e)
{
printf("Where in the array would you like to store this event\n");
int i = InputRange(1, 5) - 1;
list[i].hour = e.hour;
list[i].minute = e.minute;
strcpy(list[i].description, e.description);
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall c.c
pi#raspberrypi:/tmp $ ./a.out
__= Scheduler v1.0 =__
1. Schedule an event.
2. Delete an event.
3. Display schedule.
4. Save schedule.
5. Load schedule.
6. Exit
Please enter a number between 1 - 6
1
Enter the event time:
Please enter a number between 0 - 23
2
Please enter a number between 0 - 59
22
Enter the event description:
descr1
Where in the array would you like to store this event
Please enter a number between 1 - 5
1
__= Scheduler v1.0 =__
1. Schedule an event.
2. Delete an event.
3. Display schedule.
4. Save schedule.
5. Load schedule.
6. Exit
Please enter a number between 1 - 6
1
Enter the event time:
Please enter a number between 0 - 23
3
Please enter a number between 0 - 59
33
Enter the event description:
descr2
Where in the array would you like to store this event
Please enter a number between 1 - 5
4
__= Scheduler v1.0 =__
1. Schedule an event.
2. Delete an event.
3. Display schedule.
4. Save schedule.
5. Load schedule.
6. Exit
Please enter a number between 1 - 6
12
Invalid Entry
Please enter a number between 1 - 6
6
Exiting Program
Index #[] Time Description
[1] 2:22 descr1
[4] 3:33 descr2
note the empty line in the final print, this is because the newline is part of the description, it must be remove is present in InputEvent
Related
I am trying to make a program where the user inserts the price of a certain item of his choice, then that price is stored in a list, and the user can expand that last as he wishes, but there is a problem, even though I have the exact same arguments and parameters, the array "prices" is considered to be a pointer for some reason.
#include <stdio.h>
void ask(char ques, int index, double prices[index], double price)
{
printf("Do you want to expand your list y/n: ");
scanf("%c", &ques);
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
switch (ques)
{
case 'y':
prices[index + 1] = price;
case 'n':
main();
}
}
int main()
{
int index = -1;
double prices[index];
double price;
char ques;
ask(ques, index, prices[index], price);
}
I have this error: argument of type "double" is incompatible with parameter of type "double *"C
A solution using an array on the stack to store the prices.
prices.c
#include <stdio.h>
void ask(double prices[], int *elements, int max_elements)
{
if (*elements >= max_elements) {
printf("List is already full. (%d elements)\n", *elements);
return;
}
while (*elements < max_elements) // as long as there is space left
{
double price;
printf("What do you want the price of the next item to be: ");
scanf("%lf", &price);
prices[*elements] = price; // store price in array
*elements += 1; // increase number of elements
if (*elements == max_elements) {
printf("List is full. (%d elements)\n", max_elements);
break; // leave loop
}
char ques;
printf("Do you want to expand your list (y/n): ");
scanf(" %c", &ques);
if (ques == 'n') {
break; // leave loop
}
}
}
int main()
{
const int MAX_ELEMENTS = 10000; // 10000 prices should be enough for now
double prices[MAX_ELEMENTS]; // array to store 10000 prices
int elements = 0; // number of prices, currently none
ask(prices, &elements, MAX_ELEMENTS); // let user fill it
for (int i = 0; i < elements; i++) {
printf("%3d: %.2lf\n", i + 1, prices[i]); // print price number and price
}
return 0; // return 0 to indicate no error
}
Let's see how it works so far:
$ gcc -Wall prices.c
$ ./a.out
What do you want the price of the next item to be: 1.11
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 2.22
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 101
Do you want to expand your list (y/n): y
What do you want the price of the next item to be: 1000000.99
Do you want to expand your list (y/n): n
1: 1.11
2: 2.22
3: 101.00
4: 1000000.99
$
Test it online: https://onlinegdb.com/x1jVUU6GT
Can anyone advise why values are not getting stored in struct array?
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
This is what I tried:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int menu(void);
struct item
{
int i_SKU;
int i_QUANTITY;
int i_PRICE;
};
int main()
{
int i,j = 0;;
int n;
int input;
//struct item item1[10] = { {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0} };
struct item item1[]={0};
struct item buff[]={0};
//printf("size of %d", sizeof(item1)/sizeof(item1[0]));
printf("Welcome to the Inventory\n");
printf("===================\n");
B: printf("Please select from the following:\n");
A: menu();
scanf("%d", &input);
switch (input)
{
case 1:
printf("Inventory\n");
printf("=========================================\n");
printf("ku Price Quant\n");
for (i = 0; i < sizeof(buff)/sizeof(buff[0]); i++)
{
printf("%d %d %d\n", buff[i].i_SKU, buff[i].i_PRICE, buff[i].i_QUANTITY);
}
printf("=========================================\n");
goto B;
case 2:
//n = sizeof(item1)/sizeof(item1[0]) + 1;
//for (i=n; i < ; i++)
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
printf("Quantity:");
buff[j].i_QUANTITY=scanf("%d", &item1[j].i_QUANTITY);
printf("Price:");
buff[j].i_PRICE=scanf("%d", &item1[j].i_PRICE);
printf("The item added.\n");
j=j+1;
goto B;
case 0:
printf("bye!");
exit(1);
default:
printf("Invalid input, try again:\n");
goto A;
}
return 0;
}
int menu(void)
{
printf("1) Display.\n");
printf("2) Add to inventory.\n");
printf("0) Leave.\n");
printf("Select:");
return 0;
}
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
scanf doesn't return the value it reads, it returns the number of characters it reads.
So these lines:
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
buff[j].i_SKU=scanf("%d", &item1[j].i_QUANTITY);
buff[j].i_SKU=scanf("%d", &item1[j].i_PRICE);
don't do what you want. They put the integer into item1[j].i_X, but assign buff[j].i_X to the number of characters read.
Also, I'm guessing you intended the left hand side of those three equations to differ, not all refer to i_SKU.
Another possible problem: your buffers don't have a length specified, so they will probably just have storage for one element.
EDIT:
I'm not sure what purpose the items1 array serves in your code, but if you want the value in both arrays, you can try the following:
int sku;
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &sku);
item1[j].i_SKU = sku;
buff[j].i_SKU = sku;
// etc.
I am trying to copy the array winner from my function 'enter', so that i am able to just output it on the 'previous' function. When picking the option for the previous option I have gotten nothing outputting. Its only the last function named 'previous' that is not working, but to produce the problem the majority of the code is needed.
#include <stdio.h>
#include <string.h>
char enter(char names[][20]);
void menu();
void previous(char winner[][8]);
int main()
{
char names[16][20];
int i;
printf("Please enter the names of the players:\n");
/*Making the user enter 16 times*/
for (i = 0; i < 16; i++)
{
scanf("%9s", &names[i]);
fflush(stdin);
}
/*Clearing Screen*/
system("cls");
menu(names);
return names[16][20];
}
void menu(char names[][20], char winner[][8])
{
int choice;
printf("Please select one of the following options:\n\n"
"Press 1 to enter game results\n"
"Press 2 to display the current round\n"
"Press 3 to display the players advancing to the next round\n"
"Press 4 to display the previous round\n"
"Press 5 to exit the program\n");
scanf("%d", &choice);
if(choice == 1)
{
enter(names);
}
system("cls");
if(choice == 3)
{
previous(winner);
}
}
char enter(char names[][20])
{
int result;
int score1;
int score2;
int p, c, j, l, i;
char winner[8][8];
system("cls");
for(i = 0; i < 8; i++)
{
printf("\n\n%s vs %s",names[i],names[i+8]);
score1 = 0;
score2 = 0;
for(j = 0; j < 5; j++)
{
printf("\n\nEnter game %d results, press 1 if %s won or"
" 2 if %s won :\n",(j+1), names[i], names[i+8]);
scanf("%d", &result);
if(result == 1)
{
score1++;
}
if(result == 2)
{
score2++;
}
printf("\n\n1Current score is %d-%d", score1, score2);
if(score1 == 3)
{
printf("\n\n%s adavances to the next round!",names[i]);
strncpy(winner[i], names[i], 10);
printf("\n\nPress Enter to Continue");
getch();
system("cls");
break;
}
if(score2 == 3)
{
printf("\n\n%s adavances to the next round!",names[i+8]);
strncpy(winner[i], names[i+8], 10);
printf("\n\nPress Enter to Continue");
getch();
system("cls");
break;
}
}
}
system("cls");
printf("The players advancing to the next round are:\n\n");
for(p = 0; p < 8; p++)
{
for(c = 0; c < 8; c++)
{
printf("%c",winner[p][c]);
}
printf("\n");
}
printf("\n\nPress Enter to Continue");
getch();
system("cls");
menu(names, winner);
return winner[8][8];
}
void previous(char winner[][8])
{
int i, j;
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
{
printf("%c",winner[i][j]);
}
printf("\n");
}
}
There is no data for the array winner in your program! At least not when you call it for the first time.
The signature for the menu function is:
void menu(char names[][20], char winner[][8]);
but you call it from main like this:
menu(names);
The winner parameter is missing. This shouldn't happen, but you have declared a prototype for this function, namely:
void menu();
Unfortunately, C treats the empty parens as meaning "whatever parameters you pass", not as function that takes no parameters. That means that your function call slips by. The fix is to provide the correct signature for the prototype and also to pass a suitable winner array from main.
Strangely, your enter function provides a local array winner. This array will always be a new array when you call enter. That's probably not what you want. As is, your program should have one names and one winner array. (You can pass these arrays around, but you should make sure that tese arrays are consistent. Don't create new arrays when you really want to operate on existing ones.)
You also call your menu recursively. That means the you go ever deeper into the call structure without real benefit. Dont do that; use a loop instead: do display the menu while the user hasn't chosen "quit". (There are applications for recursive functions, but this isn't one.)
I am having problems with the menu function of my program. The last 2 parts of the printf for the menu are continuing onto the next function.
Code for menu function -
#include <stdio.h>
#include <string.h>
void enter(char names[16][20]);
void menu();
int main()
{
char names[16][20];
int i;
printf("Please enter the names of the players:\n");
/*Making the user enter 16 times*/
for (i = 0; i < 16; i++)
{
scanf("%9s", &names[i]);
fflush(stdin);
}
/*Clearing Screen*/
system("cls");
menu();
return names[16][20];
}
void menu(char names[][20])
{
int choice;
printf("Please select one of the following options:\n\n"
"Press 1 to enter game results\n"
"Press 2 to display the current round\n"
"Press 3 to display the players advancing to the next round\n"
"Press 4 to display the previous round\n"
"Press 5 to exit the program\n");
system("cls");
scanf("%d", &choice);
if(choice == 1)
{
enter(names);
system("cls");
}
}
void enter(char names[][20])
{
int result;
int score1;
int score2;
int p, c, j, l, i;
char winner[8][8];
system("cls");
for(i = 0; i < 8; i++)
{
printf("\n\n%s vs %s",names[i],names[i+8]);
score1 = 0;
score2 = 0;
for(j = 0; j < 5; j++)
{
printf("\n\nEnter game %d results, press 1 if %s won or"
" 2 if %s won :\n",(j+1), names[i], names[i+8]);
scanf("%d", &result);
if(result == 1)
{
score1++;
}
if(result == 2)
{
score2++;
}
}
}
Somehow the press 4 and 5 options are getting into the next next function
Image -
https://gyazo.com/7e99cfb42a18d04a144d3d139409d6ec
Ok.. I ran your code with some changes and it ran fine, without the two printf lines that you have shown in your image file.
First thing is, the menu() function you have written wrong. It's prototype showing that it takes no arguments while in it's declaration it take an array. You need to pass the names array to menu function as you are going to pass it to the enter function. So, both the functions menu() and enter() will be taking names array as an argument.
I used the code without system("cls") function as my compiler didn't find it.
So, it has worked at my side, I am getting feeling like, system("cls") is causing you the problem that you shown in the image.
I'm new here, so I have no idea if I posted this correctly. I did everything that the instructor told us to do for this program, but this last one has me stumped because we never talked about sorting in class. It says, "Modify the print() function so that it displays the parts sorted in ascending order by part number." I tried looking through the book and on the internet, but I just caused myself to become even more confused. Can anyone help me? Here's my code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NAME_LEN 25
#define MAX_PARTS 100
struct part {
int number;
char name[NAME_LEN + 1];
int on_hand;
float price;
};
int find_part(int number, const struct part inv[], int np);
void insert(struct part inv[], int *np);
void search(const struct part inv[], int np);
void update(struct part inv[], int np);
void print(const struct part inv[], int np);
int read_line(char [], int);
/**************************************************************
* main: Prompts the user to enter an operation code, *
* then calls a function to perform the requested *
* action. Repeats until the user enters the *
* command 'q'. Prints an error message if the user *
* enters an illegal code. *
**************************************************************/
int main(void)
{
char code;
struct part inventory[MAX_PARTS];
int num_parts = 0;
for (;;)
{
printf("Enter operation code: ");
scanf(" %c", &code);
while (getchar() != '\n') /* skips to end of line */
{
;
}
switch (code)
{
case 'i':
insert(inventory, &num_parts);
break;
case 's':
search(inventory, num_parts);
break;
case 'u':
update(inventory, num_parts);
break;
case 'p':
print(inventory, num_parts);
break;
case 'q':
return 0;
default:
printf("Illegal code\n");
break;
}
printf("\n");
}
}
/************************************************************
* find_part: Looks up a part number in the inv array. *
* Returns the array index if the part number *
* is found; otherwise, returns -1. *
************************************************************/
int find_part(int number, const struct part inv[], int np)
{
int i;
for (i = 0; i < np; i++)
{
if (inv[i].number == number)
{
return i;
}
}
return -1;
}
/****************************************************************
* insert: Prompts the user for information about a new *
* part and then inserts the part into the inv *
* array. Prints an error message and returns *
* prematurely if the part already exists or the *
* array is full. *
****************************************************************/
void insert(struct part inv[], int *np)
{
int part_number;
if (*np == MAX_PARTS)
{
printf("Database is full; can't add more parts.\n");
return;
}
printf("Enter part number: ");
scanf("%d", &part_number);
if (find_part(part_number, inv, *np) >= 0)
{
printf("Part already exists.\n");
return;
}
inv[*np].number = part_number;
printf("Enter part name: ");
read_line(inv[*np].name, NAME_LEN);
printf("Enter quantity on hand: ");
scanf("%d", &inv[*np].on_hand);
printf("Enter the price of the item: ");
scanf("%f", &inv[*np].price);
(*np)++;
}
/************************************************************
* search: Prompts the user to enter a part number, then *
* looks up the part in the inv array. If the *
* part exists, prints the name and quantity on *
* hand; if not, prints an error message. *
************************************************************/
void search(const struct part inv[], int np)
{
int i, number;
printf("Enter part number: ");
scanf("%d", &number);
i = find_part(number, inv, np);
if (i >= 0)
{
printf("Part name: %s\n", inv[i].name);
printf("Quantity on hand: %d\n", inv[i].on_hand);
printf("Item Price: %.2f\n", inv[i].price);
}
else
{
printf("Part not found.\n");
}
}
/*************************************************************
* update: Prompts the user to enter a part number. *
* Prints an error message if the part can't be *
* found in the inv array; otherwise, prompts the *
* user to enter change in quantity on hand and *
* updates the array. *
*************************************************************/
void update(struct part inv[], int np)
{
int i, number, change, userChoice, changePartNum;
float changePrice;
char *changeName[] = {""};
printf("Enter part number: ");
scanf("%d", &number);
i = find_part(number, inv, np);
if (i >= 0)
{
printf("Enter your selection to edit this particular part:\n"
"\t\t Type 1 to change the Part Number\n"
"\t\t Type 2 to change the Part Name\n"
"\t\t Type 3 to change the Price\n"
"\t\t Type 4 to change the Quantity on Hand\n"
"\t\t Type 5 to exit without making changes\n\n"
"\t\t Enter your choice here: ");
scanf("%d", &userChoice);
switch ( userChoice )
{
//printf("Would you like to change the Part Number? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 1:
printf("Enter new part number: ");
scanf("%d", &changePartNum);
inv[i].number = changePartNum;
printf("Change part num: %d\n", changePartNum);
printf("inv[i].number: %d\n", inv[i].number);
break;
//printf("Would you like to change the Part Name? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 2:
printf("Enter new name of part: ");
scanf("%s", changeName);
printf("Change part name: %s\n", changeName);
//strcpy (*changeName, inv[i].name[NAME_LEN + 1]);
//printf("&inv[i].name[NAME_LEN + 1]: %d\n", &inv[i].name[NAME_LEN + 1]);
break;
//printf("Would you like to change the price? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 3:
printf("Enter change in item price: ");
scanf("%f", &changePrice);
inv[i].price = changePrice;
break;
//printf("Would you like to change the quantity on hand? \nType 1 for yes or 2 for no.");
//scanf("%d", &userChoice);
case 4:
printf("Enter change in quantity on hand: ");
scanf("%d", &change);
inv[i].on_hand = change;
break;
case 5:
printf("Exiting the editor.");
break;
default:
printf("Your choice is not on the list.");
break;
}
}
else
{
printf("Part not found.\n");
}
}
/************************************************************
* print: Prints a listing of all parts in the inv array, *
* showing the part number, part name, and *
* quantity on hand. Parts are printed in the *
* order in which they were entered into the *
* array. * *
************************************************************/
void print(const struct part inv[], int np)
{
int i;
printf("Part Number Part Name "
"Quantity on Hand "
" Price\n");
for (i = 0; i < np; i++)
{
printf("%7d\t\t %-5s%31d\t%.2f\n", inv[i].number,
inv[i].name, inv[i].on_hand, inv[i].price);
}
}
/*************************************************************
* read_line: Skips leading white-space characters, then *
* reads the remainder of the input line and *
* stores it in str. Truncates the line if its *
* length exceeds n. Returns the number of *
* characters stored. *
*************************************************************/
int read_line(char str[], int n)
{
int ch = 0;
int i = 0;
while (isspace (ch = getchar()))
{
;
}
while (ch != '\n' && ch != EOF)
{
if (i < n)
{
str[i++] = ch;
}
ch = getchar();
}
str[i] = '\0';
return i;
}
If your professor allows you to use a function from the standard libary, check out C library function to do sort, which provides an answer that shows you how to use qsort(). If you're on linux, you can also get documentation on the function (and other standard library functions) by doing man qsort. If you're not on linux, check out any of the various online man pages.
If not, your professor probably expects you to do your own research. Generally the bubble sort algorithm is taught to beginners because of its simplicity. rosettacode provides pseudo-code on what a bubble sort should look like:
repeat
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Note that in your print function, you already have all you need, the array and its length. You demonstrated this by looping through it and printing out all the member variables. Now you just need to write the algorithm for the sort. One thing you need for the algorithm is the comparator function. You stated that you need to sort by part number. That means your comparator function will probably look like this:
int compare(struct part a, struct part b)
{
return (a.number < b.number);
}
For qsort():
qsort(inv, np, sizeof(part), compare);
In your sorting algorithm (that you should write yourself):
if (item.number at index) > (item.number at (index + 1))