Making a pause before the program ends - c

I have a question about a thingy I need to do in my code,
I need to pause the code before it ends, for example there's a switch case
for
1-etc
2-etc
3
.
.
5-etc
when i click 9 for instance,the output is
printf("This option is unknown.\nThe program exits.\n");
now what I need to do : Is after this massage the program needs to stop and when I press "enter" it will continue to "press any key to continue",
would very much appreciate the help.
EDIT: ` default:
printf("This option is unknown.\nThe program exits.\n");
getchar();
system("pause");
break;`

Try system("PAUSE"). Library needed: stdlib.h

You did not show the actual code, so it's tough saying what's actually going on there, but I'll assume your function calls an exit().
You need to add some code which waits for user input, before the control reaches the exit(). An example, getchar(), will just do the job for you.
Before you call for the exit() (or a return), you need to add
while ('\n' != getchar()); //rough way to clean input buffer
puts("press any key to continue"); //print message
getchar(); //wait for any new key press

I am very curious about your final code which resolved this issue.
I wrote a sample code that kind of mimic your situation.
Please take a look at the following code and let me know if this is what you did to fix this problem. Thanks
#include <stdio.h>
#include <string.h>
int
main(void)
{
char ch;
printf("Please enter an option [1,2,3,4,5 (return to exit):");
while( ( ch = getchar() ) !='\n' )
{
switch(ch)
{
case '1':
printf("hello 1\n");
break;
case '2':
printf("hello 2\n");
break;
case '3':
printf("hello 3\n");
break;
case '4':
printf("hello 4\n");
break;
case '5':
printf("hello 5\n");
break;
default:
printf("unknown option. Press a key to continue. (return to exit)\n");
break;
}
printf("Please enter an option [1,2,3,4,5 (return to exit):");
ch = getchar();
}
return 0;
}

Related

Function that reads the file doesn't work. Interactive menu problem

Im having some problems making my newly started project to work (also im a beginner).
For some reason option number 4 in my interactive menu doesn't work and just takes a default route (doesn't output whats inside a file (file directory is fine.).
At this point i've read every forum searching for answer but couldn't modify my code in any way that would work.
So I decided to ask you for help.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define kFileLocation "/Users/patrykpiwowarczyk/Desktop/STUDIA/FoCP/Kodowanie/TestProjektSemestralnyAngielski/TestProjektSemestralnyAngielski/authors.txt"
void options();
void start(void);
void score(void);
void optionz(void);
void author(void);
void pexit(void);
int main(void)
{
char ch;
int num;
char option;
while (1) {
printf("****Your English Learning Index Cards****\n\n");
printf("Enter 1-5 of the following options: \n\n");
options();
scanf("%c", &option);
switch (option) {
case '1':
break;
case '2':
break;
case '3':
break;
case '4':
author();
break;
case '5':
pexit();
break;
default:
printf("Please insert number ranging from 1-5 though... No cheating! \n\n");
printf("Press ENTER key to Continue\n");
}
}
return 0;
}
void options()
{
printf("1. Start Game \n");
printf("2. View Scoreboard \n");
printf("3. Options \n");
printf("4. Author \n");
printf("5. Exit \n\n");
}
void author()
{
char c;
FILE *authorsFile;
if ((authorsFile = fopen("/Users/patrykpiwowarczyk/Desktop/STUDIA/FoCP/Kodowanie/TestProjektSemestralnyAngielski/TestProjektSemestralnyAngielski/authors.txt","r")) == NULL)
{
printf("FAILED to read the file, maybe check directory?\n");
exit(1);
}
while ((c = fgetc(authorsFile)) != EOF)
{
printf("%c", c);
}
fclose(authorsFile);
}
void pexit()
{
puts("Your progress has been saved, see you next time.");
exit(0);
}
if you could help me in any way I would appreciate it soo much..
Greetings, Patryk Piwowarczyk.
PS: the #define kFileLocation is a leftover from my other tries. Omit it.
Based on your comments, I conclude the following:
The problem was that scanf correctly wrote the digit into the variable option the first time it was called. However, the second time scanf was called, it immediately returned the newline character from the previous menu selection, instead of waiting for the user to enter another digit. Whenever scanf returned a newline, the default case was triggered.
Therefore, the problem can be best solved by changing the scanf call to the following:
scanf(" %c", &option);
By adding a space to the start of the format string, you instruct scanf to discard all whitespace characters before reading the character. That way, you can insure that a newline will never be written into the option variable.
The problem of scanf reading newline characters instead of discarding them has been discussed in more detail in this question.

#default being output every time - switch case [duplicate]

This question already has an answer here:
Switch statement always including both the case and default
(1 answer)
Closed 5 years ago.
In the code below, no matter what I input, it always outputs the corresponding case statement WITH a default case statement! But when I removed the while(1){} loop, everything works fine. Why is this happening? loop's(same for for(;;) loop) fault or default case's fault? How can I change the code to print correctly within a loop?
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(){
char ch;
puts("Client Management System");
puts("========================");
puts("A: add task");
puts("D: delete task");
puts("U: modify task");
puts("Q: quit system");
while(1){
ch = getchar();
ch = toupper(ch);
switch(ch){
case 'A':
puts("adding task......");
break;
case 'D':
puts("deleting task......");
break;
case 'U':
puts("modifying task......");
break;
case 'Q':
return 0;
default:
puts("invalid option");
}
}
return 0;
}
Additional case needs to be added to handle '\n' condition. This is because when you type a case in the console and press enter key, '\n' also be included. So handling this would eliminate the default case execution.

C: Problems with using getchar and switch case to get user input for a main menu

I know there are many threads similar to this one, however, those threads didn't really help me out. I am new to C, so I might be just making a silly mistake, but I don't know what I'm doing wrong.
I am trying to create a main menu like this:
Main menu:
1. Play
2. Reset
3. Display
When users press 1, I want it to print play game, when 2 is pressed, I want it to print Reset, and so on.
However, with my code, when user presses 1, it prints "play game", and when users presses 2 or 3, it doesn't print anything.
int main(){
int input;
/*Displays the menu to user*/
printf("Main menu\n");
printf("1.Play\n");
printf("2.Reset\n");
printf("3.Display\n");
printf("please enter something:\n");
input=getchar();
switch(input){
case'1':
printf("play game\n");
break;
case'2':
printf("reset\n");
break;
case'3':
printf("Display\n");
break;
default:
printf("invalid\n");
break;
}
{
getchar();
while(input != '3');
}
return EXIT_SUCCESS;
}
So I know I might be making a silly mistake, but I just can't figure what I am doing wrong. I have also looked at other threads and none them have helped me.
I think you are looking for do-while loop. You want to nest your switch inside this do-while to repeatedly execute it.
Also, note the extra getchar() call to consume the Enter that was typed after the number.
#include <stdio.h>
#include <stdlib.h>
int main(){
int input;
/*Displays the menu to user*/
printf("Main menu\n");
printf("1.Play\n");
printf("2.Reset\n");
printf("3.Display\n");
printf("please enter something:\n");
do{
input=getchar();
getchar();
switch(input){
case'1':
printf("play game\n");
break;
case'2':
printf("reset\n");
break;
case'3':
printf("Display\n");
break;
default:
printf("invalid\n");
break;
}
} while(input != '3');
return EXIT_SUCCESS;
}

What's while doing here in the code?

In the following piece of code what is while loop doing (marked with "loop")?:-
int main(void)
{
char code;
for (;;)
{
printf("Enter operation code: ");
scanf(" %c", &code);
while (getchar() != '\n') // loop
;
switch (code)
{
case 'i':
insert();
break;
case 's':
search();
break;
case 'u':
update();
break;
case 'p':
print();
break;
case 'q':
return 0;
default:
printf("Illegal code\n");
}
printf("\n");
}
}
Diclaimer:The code is not complete, it's just a part of the code because of which it won't compile.
getchar() used here to eat up the extra characters entered by user and the newline character \n.
Suppose a user entered the operation code as
isupq\n // '\n' is for "Enter" button
then, scanf() would read only character i and rest of the five characters would become consumed by the statement
while (getchar() != '\n')
;
Thus for next iteration scanf() will wait for user to input a character instead of reading it from the input buffer.
while (getchar() != '\n') // loop
;
is here to clean the buffer.
The problem that this while solves is that scanf(" %c", &code); only grabs a single character from the input buffer. This would be fine, except that there's still a newline left in the input buffer that resulted from hitting 'enter' after your input. a buffer clear is needed for the input buffer. that's what the while loop does
it is a common problem with c
Here application waits for the user to press enter.
Since the for loop in the given code is a infinite looping so the while loop is checking whether the input character is \n or not. In case the the character entered is \n it then moves toward the switch case. In general sense it is waiting of return key to be pressed to confirm your input.
if you use the fgetc function you don't have to worry and check for the enter key in your infinite loop. Even if you enter more than one character it will only take the first one
int main(void)
{
char code;
for (;;)
{
printf("Enter operation code: ");
code = fgetc(stdin);
switch (code)
{
case 'i':
insert();
break;
case 's':
search();
break;
case 'u':
update();
break;
case 'p':
print();
break;
case 'q':
return 0;
default:
printf("Illegal code\n");
}
printf("\n");
}
}
scanf() usually is not a good way to scan char variables, because the Enter you press after entering the character remains in input buffer. Next time you call scanf("%c", &input) this Enter already present in buffer gets read & assigned to input, thus skipping next input from user.

Code giving me an infinite loop

#include <stdio.h>
void load_menu(void);
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
int loopagain;
do
{
printf("Menu \n\n");
printf("Please enter your choice: \n");
printf("1. \n");
printf("2.\n");
printf("3.\n");
printf("4. Exit\n");
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4: printf("Quitting program!\n");
break;
default: printf("Invalid choice! Please try again\n");
printf("\n");
break;
}
}
else
{
printf("Characters are invalid, please enter a number: \n ");
if (scanf("%d",&loopagain)==1)
load_menu();
}
}while((choice !=4));
}
why is this still giving me an infinite loop when I enter a character? It is a menu (the case statements still need to be filled) but i am taking care of the character input by the if statement but it still does not seem to work. Thanks
If the character input is invalid, the loopagain in the newly-called load_menu() won’t be the same as in its caller. Don’t recurse at all:
else
{
printf("Characters are invalid, please enter a number: \n ");
choice = 0; // Unused, so continue the loop
}
I believe, aside from the problems identified so far, is that the offending "letter" is stuck in the input buffer. When reading a number with scanf, it stops as soon as it hits anything not whitespade and not a digit. So if the buffer contains "a\n", and we call scanf("%d", ...), then scanf will return immediatelty, and will keep on doing so until the offening 'a' has been removed from the buffer.
What we need is a little loop to remove the offending "rubbish" from the input buffer.
Here's that question asked before (although the flushing is for a slightly different reason, the solution is the same):
Question about flushing buffer
After you enter something the is not a digit, and as such is not accepted by scanf("%d",&choice) the input buffer is not flushed. I believe you should be able to fix this issues with a call to fflush(stdin) when handling unacceptable inputs. Better, you would probably be better servde to flush the input buffer after each time you call scanf.
To my mind, your handling of an incorrect input doesn't make sense. It should be handled more like your default: case, I think. The recursive call, as has been stated by others, doesn't make sense, nor does calling scanf again for input when you are about to go back to displaying the menu and getting user input yet again.
I think your problem is the loopagain variable. By the name, you were thinking about this variable like a flag to loop or not again and to manage the way your second loop would go. Since you are reading it from stdin(scanf) you'll lost the control over it.
Since you already have one scanf in your implementation and since it is a loop, you won't need recursive calls and you can use always the same scanf, using the loopagain variable/flag in the proper way.
Even better is that in this way, there's no char wich its integer value is 4(it woul never pass the scanf test with value 1, but still...) besides the EOT (ascii - cntr-D) wich is a non-common one, and you can think of it as an alternative way to break your program.
One soluiton is this(I guess, by my interpretation) :
#include <stdio.h>
void load_menu(void);
int main(void)
{
load_menu();
return 0;
}
void load_menu(void)
{
int choice;
int loopagain = 1;
do
{
if(loopagain != 0){ /*You'll set it to different from 0 if the user entered a 'bad' number so the menu is only printed once*/
printf("Menu \n\n");
printf("Please enter your choice: \n");
printf("1. \n");
printf("2.\n");
printf("3.\n");
printf("4. Exit\n");
}
if (scanf("%d",&choice)==1)
{
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4: printf("Quitting program!\n");
break;
default:printf("Invalid choice! Please try again\n");
loopagain = 0;
printf("\n");
break;
}
}else{
printf("Characters are invalid, please enter a number: \n ");
loopagain = 0;
}
}while(choice !=4);
}
Hope it helped.

Resources