Switch Case not working after using scanf [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
The issue I have is that after entering a value to be used by the variable action, the program immediately ends without doing any of the cases inside the switch. Will post the other functions if needed, but otherwise, I will refrain because it's too long and it will flood the page. Can anyone tell me why this is happening?
Driver code and output are shown below:
int main()
{
// Creation of empty list
struct Node* head = NULL;
bool print = false;
int action, placeNum, numIndex;
while (print == false){
printf("LINKED LIST CREATOR \n");
printf("1. Insert node at the beginning\n");
printf("2. Insert node at the end\n");
printf("3. Insert node at specified position\n");
printf("4. Delete node at the beginning\n");
printf("5. Delete node at the end\n");
printf("6. Delete node at specified position\n");
printf("7. Display the linked list\n");
printf("Please enter the action you want to do: ");
scanf("%d", action);
switch (action)
{
case 1:
printf("Enter the number to be placed at the beginning: ");
scanf("%d", placeNum);
insert_first(&head, placeNum);
break;
case 2:
printf("Enter the number to be placed at the end: ");
scanf("%d", placeNum);
insert_last(&head, placeNum);
break;
case 3:
printf("Enter the index for the number to be placed: ");
scanf("%d", numIndex);
printf("\nEnter the number to be placed at specified index: ");
scanf("%d", placeNum);
insert_middle(numIndex, placeNum, &head);
break;
case 4:
delete_first(&head);
break;
case 5:
delete_last(head);
break;
case 6:
printf("Enter the index of the number to be deleted: ");
scanf("%d", numIndex);
delete_middle(&head, numIndex);
break;
case 7:
printf("\nThe Created Linked List is: ");
printList(head);
print = true;
break;
}
}
return 0;
}
PS C:\Codes> cd "c:\Codes\C++\" ; if ($?) { g++ singlelist.cpp -o singlelist } ; if ($?) { .\singlelist }
LINKED LIST CREATOR
1. Insert node at the beginning
2. Insert node at the end
3. Insert node at specified position
4. Delete node at the beginning
5. Delete node at the end
6. Delete node at specified position
7. Display the linked list
Please enter the action you want to do: 1
PS C:\Codes\C++>

You're not using scanf correctly:
scanf("%d", action);
The %d format specifier expects the address of an int (i.e. an int *) but you're instead passing an int, and an uninitialized one at that. Using the wrong argument type for a format specifier triggers undefined behavior.
If you pass the address:
scanf("%d", &action);
You'll get the result you expect. You'll want to do the same for you other scanf calls that use %d.

scanf receives a format string and a POINTER to the variable where it will be stored.
So in this case the line should be:
scanf("%d", &action);

Related

how to check availability seats in c code linked list

I want to show the availability of the seats in linked list, but I don't know somehow the logic in the chekcavailability() doesn't work.
First input is okay, the second input when I entered the same value it shows seat has been taken and return back to the particular function.
But when I enter again the different value which is available, it gives me an error.
Please help thank you.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define A 20
struct passenger
{
char name[20];
char booking_id[20];
char passno[20];
char seatno[20];
struct passenger *next;
}*start,*curr;
void datainput(), savefile(), loadfile(), checkavailability(), validationseat();
int main()
{
void reserve_seat(), cancel_seat(), modify_seat(), display_layout(), exit();
int choice;
start=curr=NULL;
do
{
system("cls");
printf("\n\n*************************************************");
printf("\n\n********AIRLINE RESERVATION MENU*****************");
printf("\n\n*************************************************");
printf("\n\n\t\t* 1. Reserve seat *");
printf("\n\n\t\t* 2. Modify seat *");
printf("\n\n\t\t* 3. Cancel seat *");
printf("\n\n\t\t* 4. Display seat layout*");
printf("\n\n\t\t* 5. Exit *");
printf("\n\n*************************************************");
printf("\n\n\n\n\t\t Enter your choice: ");
scanf("%d",&choice);fflush(stdin);
switch (choice)
{
case 1:
reserve_seat();
break;
case 2:
modify_seat();
break;
case 3:
cancel_seat();
break;
case 4:
display_layout();
break;
case 5:
{
exit();
break;
}
default:
printf("invalid choice!!, please try again");
}
getch();
}while (choice != 5);
}
void datainput()
{
printf("\n\t\t enter your booking ID: ");
gets(curr->booking_id); fflush(stdin);
printf("\n\t\t enter your seat number: ");
gets(curr->seatno); fflush(stdin);
printf("\n\t\t Enter Name: ");
gets(curr->name); fflush(stdin);
printf("\n\t\t Enter Passport Number: ");
gets(curr->passno); fflush(stdin);
}
void reserve_seat()
{
curr=start;
checkavailability();
if(start==NULL)
{
start=curr=(struct passenger *)malloc(sizeof(struct passenger));
datainput();
curr->next=NULL;
printf("\n\t data has been recorded");
return;
}
while(curr->next=NULL)
curr=curr->next;
curr->next=(struct passenger *)malloc(sizeof(struct passenger));
curr=curr->next;
datainput();
curr->next=NULL;
printf("\n\t data has been recorded");
void checkavailability()
{
int i;
char cmp3[20];
printf("select your seat(1-20)");
gets(cmp3);fflush(stdin);
while(curr)
{
if (strcmp(curr->seatno, cmp3)==0)
{
printf("Seat has been taken\n");
checkavailability();
}
else
{
break;
}
}
printf("seat available");
return;
}
There are many error with your code, and the worst is that he cannot compile (unless conio declare an exit function with no parameter).
First, you need to activate a decent compiler option. At least -Wall -Wextra (depend of the compiler).
In main function, this : exit();
The exit function need a parameter. Fix that.
modify_seat();
cancel_seat();
display_layout();
These function aren't implemented, so you shouldn't make a call to them. Fix that either.
Do not use gets ! It's dangerous and unsafe.
Do not fflush(stdin) ! It's undefined behavior.
The "A" define is useless and not really explicite. What was it supposed to be ? "Array" ?
For your safety, try to not use global variable.
I suggest to define a structure and declare a variable in main.
In "reserve_seat" :
while(curr->next=NULL)
you made a mistake here : it's while(curr->next != NULL)
You assign NULL to curr->next, maybe it's the reason that why your linked list is broken.
Well, it's a dirty code for me, because it severly lack rigourous coding.
For example, check if your function call failed (like malloc).
I suggest you to rewrite the code.

Basic Linked List operations in C

I am creating a program to perform basic linked list operations. Right now i have wrote the code only for inserting the node at the front. I ran my program to see its working or not but the program is terminating after accepting the input for the node, then it prints the message after switch. It doesn't even pause for accepting my input for continuing the operations (just before end of main())
here is the code :
#include <stdio.h>
#include <stdlib.h>
struct linkedlist
{
int num;
struct linkedlist *next;
};
struct linkedlist *head = NULL;
void display();
void insertBeginning()
{
struct linkedlist *obj;
int no;
obj = (struct linkedlist *)malloc(sizeof(struct linkedlist));
if(obj == NULL)
{
printf("\n Overflow ");
}
else
{
printf("\n Enter the number = ");
scanf("%d", &no);
obj->num = no;
if(head == NULL)
{
head = obj;
obj->next = NULL;
}
else
{
obj->next = head;
head = obj;
}
}
}
void display ()
{
struct linkedlist *head2 = head;
while(head2 != NULL)
{
printf("%d ->",head2->num);
head2=head->next;
}
printf("NULL \n");
}
int main()
{
int choice;
char wish;
printf("\n 1. Insert at beginning");
printf("\n 2. Insert at end");
printf("\n 3. Insert in between");
printf("\n 4. Delete from front");
printf("\n 5. Delete from end");
printf("\n 6. Delete from in between");
printf("\n 7. Reverse");
printf("\n 8. Sort ascending");
printf("\n 9. Sort descending");
printf("\n 10.Swap alternate elements");
printf("\n 11.Display\n\n");
do
{
printf("\n Enter the option = ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insertBeginning();
break;
case 2:
// insertEnd();
break;
case 3:
// insertInbetween();
break;
case 4:
// deleteFront();
break;
case 5:
// deleteEnd();
break;
case 6:
// deleteInbetween();
break;
case 7:
// Reverse();
break;
case 8:
// sortAsc();
break;
case 9:
// sortDesc();
break;
case 10:
// swap();
break;
case 11:
display();
break;
default:
printf("\n Wrong choice ");
}
printf("\n Do you wish to continue (y/n) = ");
scanf ("%c",&wish);
}while(wish == 'y' || wish =='Y');
return 0;
}
In your case, you have to change
scanf ("%c",&wish);
to
scanf (" %c",&wish);
because, if you don't include the leading white-space before the format specifier, it will consider the remaining \n (newline) which got generated and stored into the input buffer by pressing ENTER key after the first input. So, the second scanf() won't wait for the user input.
when calling scanf()
1) with a '%d' format specifier, the trailing newline, from where the user entered the number, will not be consume.
2) with a '%c' format specifier, leading white space, like a newline, will cause the scanf() to fail, leaving the parameter (wish) unchanged.
3) in the posted code, when the 'wish' does not contain a valid 'Y' or 'y' then the program exits.
I agree with the other poster, that adding a choice '0' for exiting would be a much better way than the separate call to scanf()
there is a new line after giving the input 'choice' which scan by the variable 'wish'. So we need to remove that newline ('\n').
So if you want the user to continue just use a getchar() before take the input wish. Its easy and simple.
printf("\n Do you wish to continue (y/n) = ");
getchar();
scanf ("%c",&wish);

sort/search in stack [duplicate]

This question already has an answer here:
How to sort an array of structs in C?
(1 answer)
Closed 8 years ago.
I have created a stack system in C
It takes the First Name, Last name, and an employee number and the program runs fine.
#include<stdio.h>
#include<conio.h>
#define MAX 20
struct system
{
char first_name[15];
char surname[15];
}employee[20], temp;
int stack[MAX],front=-1,top=-1;
int i;
void push_element();
void pop_element();
void display_stack();
void display_first();
int main()
{
int option;
printf("STACK PROGRAM");
do
{
printf("\n\n 1.Push an element");
printf("\n 2.Pop an element");
printf("\n 3.Display stack");
printf("\n 4.Display first");
printf("\n 5.Display last");
printf("\n 6.Exit");
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1: push_element();
break;
case 2: pop_element();
break;
case 3: display_stack();
break;
case 4: display_first();
break;
case 5: display_last();
break;
case 6: return 0;
}
}while(option!=6);
}
void push_element()
{
printf("\n Enter the first name: ");
scanf("%s",employee[i].first_name);
printf("\n Enter the Last name: ");
scanf("%s",employee[i].surname);
int num;
printf("\n Enter the employee number: ");
scanf("%d",&num);
i++;
if(front==0 && top==MAX-1)
printf("\n You have entered more than 20. Please delete a current input to make room. ");
else if(front==-1&&top==-1)
{
front=top=0;
stack[top]=num;
}
else if(top==MAX-1 && front!=0)
{
top=0;
stack[top]=num;
}
else
{
top++;
stack[top]=num;
}
}
void pop_element()
{
top--;
return top;
}
void display_stack()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n List of employees:\n\n ");
printf(" Employee number First Name Surname\n\n");
for(i=front;i<=top;i++)
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
void display_first()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n The first Employee in the stack is:\n\n ");
printf(" Employee number First Name Surname\n\n");
for(i=front;i<=top;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
void display_last()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n The last Employee in the stack is:\n \n");
printf(" Employee number First Name Surname\n\n");
for(i=top;i<=front;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
I for the life of me cannot figure out how to sort the stack. I have tried other pieces of code and many different things, but none of them have came close to finding it
But I am wanting to sort it by alphabetical order. So not by entry time or Employee number, but by the First initial of the Surname
A search function is also required for this, and to be done by Employee number.
I have looked online, and the use of sorting and searching in a stack isn't a common thing, but I required to have it.
I am not good at C and I am fairly new to it. Any tips or things that may help me greatly would be appreciated. Also I apologies for any formatting errors, I'm fairly new to programming altogether and using software.
Your data structure doesn't directly record an employee number. You have the array stack which records the employee number, and the array employee which records names. You need to preserve the relationship stack[i] contains the employee number for employee[i] which means any sorting of the existing data structure has to sort two arrays in parallel. While it can be done, it is not the best way to fix the problems (and it is harder than it need be, and will require a custom sort function).
You should upgrade the data structure to include the employee number:
struct employee
{
int number;
char first_name[15];
char surname[15];
} employee[20];
Note that I've retagged the structure as struct employee (instead of struct system) since it seems more relevant to the content of the structure.
You can then use the qsort() function from the standard C library (declared in <stdlib.h>) and the techniques documented in the proposed duplicate (How to sort an array of structs in C?) to sort the data straight-forwardly. It is also easier to write your searching code.
You can also clean up the display code; you can have a single function that is passed an employee structure (or pointer to one). It will contain a single printf() statement that formats the data correctly. This saves you writing the same elaborate printf() code 3 times, making it easier to fix the formatting if (when) you need to do so. You can also avoid using tabs in the output (generally a good idea), leading to:
void print_employee(const struct employee *emp)
{
printf("%8d %-15s %-15s\n", emp->number, emp->first_name, emp->surname);
}
This will produce well aligned output unless your employee number grows to more than 8 digits (in which case, change the 8 to 10 or whatever). You can also generalize one step further if you wish, passing a FILE *fp argument to the function, and using fprintf(fp, "…", …) instead of printf().
You call the function:
print_employee(&employee[i]);
You might also consider a function to print the headings since you have that function call 3 times. Alternatively, you might just have a constant string at file scope that contains the correct headings which you use in 3 places. You could do that with the print_employee() function too; have a constant string at file scope that is the format you use.
Also, in your display_first() and display_last() functions, the loops are curious. You've written:
for(i=front;i<=top;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
You should realize (on review) that this is equivalent to:
i = front;
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
(If front is larger than top, then i = front is the only part of the loop executed; otherwise, the break is executed; either way, after the loop, i == front.)

c programming: stopping endless loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have been trying to get my head around validating the code, a.k.a stopping the program from breaking and entering the endless loops but I find it quite difficult.
So far I have come across multiple points in the program where the user can break it by entering the wrong input for example with the main menu if the user enters a letter or symbol instead of a number the program enters the endless loop, so a basic guide on validating would be helpful.
#include <stdio.h>
#include <stdlib.h>
struct packet{
int source;
int destination;
int type;
int port;
char data[50];
};
void main ()
{
struct packet s[50]; //Array for structure input
int choice;
int customerCount = 0, ii = 0;
while (customerCount <= 50){
printf("What would you like to do?\n");
printf("\t1) Add a packet.\n");
printf("\t2) s all packets.\n");
printf("\t3) Save packets.\n");
printf("\t4) Clear all packets.\n");
printf("\t5) Quit the programme.\n");
scanf("%i", &choice);
switch (choice)
{
case 1: printf("\n****Adding a packet*****\n");
printf("Where is the packet from?\n");
scanf("%i", &s[customerCount].source);
printf("Where is the packet going?\n");
scanf("%i", &s[customerCount].destination);
printf("What type is the packet?\n");
scanf("%i", &s[customerCount].type);
printf("What is the packet's port?\n");
scanf("%i", &s[customerCount].port);
printf("Enter up to 50 characters of data.\n");
scanf("%s", s[customerCount].data);
customerCount++;
break;
case 2: printf("\nDisplaying Infomation\n");
for(ii = 0; ii < customerCount; ii++) {
printf("\nSource: %d", s[ii].source);
printf("\nDestination: %d", s[ii].destination );
printf("\nType : %d", s[ii].type);
printf("\nPort : %d", s[ii].port);
printf("\nData: %s\n---\n", s[ii].data);
}
break;
case 3: break;
case 4: break;
case 5: break;
default: printf("\nThis is not a valid choice, please choose again\n\n");
break;
}
}
}
scanf returns the number of arguments it successfully scanned.
Checking for proper input and rejecting bad input can be as simple as:
printf("Where is the packet from?\n");
while(scanf("%i", &s[customerCount].source) != 1)
{
while(getchar() != '\n')
continue;
}
This is not very robust, however, and something like validating user input should be very robust. Assume the user will always enter wrong input... it's sad but true.

Having an issue with structs and the program not saving inputs. I am inexperienced [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The compiler doesn't come up with any errors...It is supposed to be a basic phonebook with 5 slots for people. For some reason everything seems to work but it doesn't save the information. What did I do wrong?
typedef struct contact{
char fname[10];
char lname[10];
int pnumber;
};
struct contact p1;
struct contact p2;
struct contact p3;
struct contact p4;
struct contact p5;
int go =0;
int phonebook(struct contact person,int use);
int main(){
while(go == 0){
int contact;
int choice;
int location;
printf("first what position in your contacts would you like to change?(1-5)\n");
scanf("%d",&location);
printf("what would you like to do?\n1. add a contact\n2. change a contact\n3. print a
contact\n4. Quit\n");
scanf("%d",&choice);
switch(location){
case 1:
phonebook(p1,choice);
break;
case 2:
phonebook(p2,choice);
break;
case 3:
phonebook(p3,choice);
break;
case 4:
phonebook(p4,choice);
break;
case 5:
phonebook(p5,choice);
break;
default:
printf("that was not a valid option\n");
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
int phonebook(struct contact person,int use){
switch(use){
case 1:
if(person.pnumber>0){
printf("you already have a contact there\n");
}
else{
printf("What is the contact's first name?\n");
scanf("%s", &person.fname);
printf("\nWhat is the contact's last name?\n");
scanf("%s", &person.lname);
printf("\nWhat is the contact's phone number?\n");
scanf("%d", &person.pnumber);
}
break;
case 2:
if(person.pnumber == 0)
printf("No contact is saved in this position\n");
else{
printf("What is the contact's first name?\n");
scanf("%s", &person.fname);
printf("\nWhat is the contact's last name?\n");
scanf("%s", &person.lname);
printf("\nWhat is the contact's phone number?\n");
scanf("%d", &person.pnumber);
}
break;
case 3:
printf("\nName:%s\n%s \nNumber:%d \n",&person.fname,&person.lname,&person.pnumber);
break;
case 4:
go = 1;
break;
default:
printf("that wasn't an option. Please pick a valid option next time.\n");
}
}
You have a simple problem: the C language uses "call by value", so your phonebook() function gets a copy of the struct. Then the phonebook() function changes the copy, but the changes aren't saved anywhere.
The way you fix this: you have to make your phonebook() function take a pointer to a struct, and then it can use the pointer to modify the struct.
int phonebook(struct contact *pcontact, int use)
{
// ... stuff omitted ...
printf("What is the contact's first name?\n");
scanf("%s", pcontact->fname); // "fname" works as a pointer
printf("\nWhat is the contact's phone number?\n");
scanf("%d", &pcontact->pnumber); // must take address of integer "pnumber"
// ... rest of phonebook() omitted ...
// example of calling phonebook():
case 1:
phonebook(&p1, choice);
http://www.lysator.liu.se/c/bwk-tutor.html#pointers
You are passing person by value, not by reference, so phonebook is making changes to a copy of the contact struct.
Try
int phonebook(struct contact *person,int use);

Resources