How to make a program shut itself down - c

How do I make a program shut itself down after user says y in case 3. I want when they press y in case 3 that program exits it self like it would when compiling is done. I'm trying to make a menu where you can browse trough the options its not complete yet I need to make play, graphics, sounds case. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main()
{
int op1;
printf("1.Play\n");
printf("2.Options\n");
printf("3.Exit\n");
scanf(" %d", &op1);
char ans;
switch(op1)
{
case 1 : printf("Press 5 to start a new game");
break;
case 2 : printf("1.Graphics\n"); printf("2.Sound\n");
break;
case 3 : printf("Are you sure (y/n)");
scanf(" %c", &ans);
if(ans =='y')
{
}
else
{
printf("1.Play\n");
printf("2.Options\n");
printf("3.Exit\n");
}
default : printf("Wrong choice.");
}
return 0;
}

If this is to be restricted to the main() method, then just return out.
if(ans == 'y') {
return 0;
}
It is a good practice to avoid hard exits unless you really need them.
But if you really need to hard exit out, you may try _exit(0); here. exit(0); as well, which has already been mentioned.

First of all, y is not a variable, you have to compare with the character code:
if (ans == 'y') {...}
To terminate your program, use:
exit(0);

Related

C program doesn't wait for user input with scanf()

I'm new to C and this is my TicTacToe for first C project. For that, I setup a simple process for user where to choose X or O. But it doesn't seem to work for reason. Here it continues to the if statements and goes into infinite loop cause it didn't wait for user input.
I've gone through similar forums about this exact question but I was unable to get an answer that fixed my problem. Also, feedbacks about the code are much appreciated because I do want to improve my code.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char checks_player;
int is_input_valid = 0;
while(is_input_valid == 0)
{
printf("What do you want to choose? (X/O) ");
scanf(" %c",checks_player);
if(checks_player == 'x')
{
checks_player = 'X';
is_input_valid = 1;
}
else if(checks_player == 'o')
{
checks_player = 'O';
is_input_valid=1;
}
else if((checks_player == 'O')|| (checks_player == 'X'))
{
is_input_valid = 1;
}
else
{
printf("Invalid Input!!\nTry Again.\n\n");
}
}
}
You need to pass a pointer to scanf. Instead of this:
scanf(" %c",checks_player);
Use this:
scanf(" %c", &checks_player);

How to repeat the main () function without closing the program?

I am trying to make a password generator. Everything was going smoothly until I tried to repeat the main function at the end. The code goes like this:
I also would appreciate feedback on the code. I am still learning (when do we stop learning though?) and I want to improve as much as I can and as fast as I can.
// password generator
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main ()
{
char answer;
int c=0;
int passlength;
char randLWUPchar; // lowercase, uppercase, characters + numbers
srand(time(NULL)); // seeding function
printf("Type the wished password length:");
scanf("%d", &passlength);
while(c < passlength){
randLWUPchar = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"[rand () % 65];
printf("%c", randLWUPchar);
c++;
}
printf("\n\n\t\t...if it fails to prompt as wished, please restart...\n");
printf("\n\n\t\t Please select Y to restart or N to close");
scanf("%c", &answer);
if (answer == 'Y'){
return main();
}
else if (answer == 'N'){
return EXIT_SUCCESS;
}
}
I'd recommend refactoring your function to not use recursion.
With optimizer on full blast this tail call should be easy to optimize out, but you shouldn't be depending on the optimizer. Use a loop instead.
Try something like:
do
{
// your code
} while(answer == 'Y');
return ERROR_SUCCESS;
Contrary to what is said in comments, yes, your main() can be recursive.
As mentionned by #Keith Thompson, you must flush the '\n' after reading your passlength. For example:
scanf("%d", &passlength);
fgetc(stdin);
Then
scanf("%c", &answer);
fgetc(stdin);

Unexpected call of printf

This is the first question I've posted about C programming on here as I just started learning C just a few weeks ago. Ill write up my code and ask what my problem is :) If Anyone please knows how I can fix my mistake or whatever I should replace for my code please reply:)!
The problem I am having, is that if you run the code for yourself, you will see that everything works fine, except for the 'else' part in the statement. The issue I am having is that when someone types more than one letter, it will run the last printf statement more than once, and will printf as many times as the user inputs a character other than y or n.
The first part with the Y or N is working fine, yet if they type any number of other chars, it doesnt just state "Please select again", one time and then re-scanf, it types out at least 2 printfs, just for even one character entered, "Please select again" "Please select again", and then, if you type more chars for the answer, it will just type even more "please select again"'s.
Please help me understand what I am doing wrong as I'm so keen on learning to program properly, but I am just stuck here atm :)
#include <stdio.h>
#include <conio.h>
int main()
{
char answer;
int loop = 0;
printf("Please select. [Y/N]:\n");
while (loop == 0)
{
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
{
printf("Seeyou Later Aligator.\n");
break;
return 0;
}
else if (answer == 'n' || answer == 'N')
{
printf("Mmkay.\n");
break;
return 0;
}
else
{
printf("Please select again [Y/N]:\n");
loop = 0;
}
}
getch();
return 0;
}
scanf reads the required number of characters each time. If there are more characters, they are not ignored. They are read next time you call scanf. Hence you see multiple prints for every character. Inorder to explicitly ignore pending input, call fflush(stdin) after scanf. Which means to flush out any data in standard input stream.
Update:
fflush should not be used on input streams as said in comments. Use the accepted solution for ignoring output. However I recommend using toupper or tolower instead of bit hack.
The reason as many have pointed out is that your scanf is reading the extra newline character left in the input buffer after the user presses ENTER. So here is an alternative way to read input to avoid that whole mess:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char answer;
printf("Please select. [Y/N]:\n");
while (1)
{
scanf("%1s%*[^\n]", &answer);
answer |= 0x20;
if (answer == 'y')
{
puts("Seeyou Later Aligator.");
break;
}
else if (answer == 'n')
{
puts("Mmkay.");
break;
}
else
{
puts("Please select again [Y/N]:");
}
}
getchar();
return 0;
}
This will read just the first character found on stdin and ignore everything else after that and at the same time clear the input buffer of the newline character
break; is enough ... return will never be executed as you will break out of the while
Its printing more than once because scanf is taking in '\n' and extra inputs from previous entry
also the variable loop is pointless in your code
here is the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char answer;
int loop = 0;
printf("Please select. [Y/N]:\n");
while (1)
{
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
{
printf("Seeyou Later Aligator.\n");
break;
//return 0;
}
else if (answer == 'n' || answer == 'N')
{
printf("Mmkay.\n");
break;
// return 0;
}
else
{
printf("Please select again [Y/N]:\n");
while(getchar()!='\n'){
getchar();
if(getchar() == '\n'){
break;
}
}
}
}
getchar();
return 0;
}
Output:
$ ./test
Please select. [Y/N]:
dddd
Please select again [Y/N]:
ffffff
Please select again [Y/N]:
y
Seeyou Later Aligator.

How to set a string to perform a function or command

I kind of have a basic question for you because it's driving me crazy. How do I go about writing my functions to specific strings? Like, if I was creating a while loop and wanted the program to end, how would I write it so that the program itself ends when I type in "end" when it asks for input?
EDIT: Alright, so I figured out pretty easily how to end my function by typing "end", but now for some reason depending on how many sentences I write, my program keeps repeating itself.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int i;
char buf[10];
printf("Command? ");
scanf("%s", buf);
while(buf != "end")
{
if(strcmp(buf, "end")== 0){
break;
}
switch( buf[i] ){
//Where the cases will inevitably go
default:
puts("I'm sorry, but that's not a command.\n");
break;
}
printf("Command? ");
scanf("%s", buf);
}
puts("End of Program.");
getch();
}
char *myInputString = NULL;
while (1) {
/* read in myInputString from user input, and test... */
if (strcmp(myInputString, "foo") == 0)
break;
}
return EXIT_SUCCESS;

Scanf causes C program to crash

This simple issue is causing my entire program to crash during the first input. If I remove the input, the program works fine but once I add scanf into the code and enter the input the program crashes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXEMPS 3
// stub program code
int main (void){
char answer;
do
{
printf("\n Do you have another(Y/N): ");
scanf("%c", answer);
}while(answer == 'Y' || answer == 'y');
getchar();
printf(" Press any key ... ");
return 0;
} // main
You must pass the address of the variable to scanf:
scanf("%c", &answer);
Use "&answer". And get rid of the extraneous "fflush()" commands...
Better, substitute "answer = getchar ()".

Resources