Getting user to choose whether or not to exit program - c

I am trying to end a program by giving the user the option whether to loop back to the start or exit. I've pasted this portion of the program below; 'homenumber' is where it should loop back to and is defined at the start of the program.
#include <stdio.h>
int main(void)
{
char option[1];
/*Asks if user wants to exit program*/
printf("Do you want to close the program? [Y/N]: ");
scanf_s("%c",&option,1);
if (option == "N" || option == "n") {
goto homenumber;
}
else if (option == "Y" || option == "y") {
;
}
Thanks in advance.
edit: My problem is the program won't let me enter a value for 'option' - it just ends the program no matter what

You should make option a char instead of a character array:
#include <stdio.h>
int main(void)
{
...
homenumber:
...
char option;
/* Ask if user wants to exit program */
printf("Do you want to close the program? [Y/N]: ");
option = 'Y';
scanf_s("%c",&option);
if (option == 'N' || option == 'n') {
goto homenumber;
} else
if (option == 'Y' || option == 'y') {
;
}
Note that you should also check the return value of scanf_s. I am setting option before the call as a quick and dirty solution. Using getchar() instead of scanf_s would be simpler and less error prone.
I am not condoning the use of goto either, just pointing at the actual issue you have trouble with.

Related

While loop causing many issues with program

void answerme();
int main() {
char *answer = malloc (MAX_NAME_SZ);
....
printf ("\nWould you like to begin? [Y/N]");
fgets (answer, MAX_NAME_SZ, stdin);
answerme();
if(*answer == 'y' || *answer == 'Y'){
getinfo();
printf("\nprogram starting now...");
}
else if(*answer == 'n' || *answer == 'N'){
printf("\nThank you, program will close now....");
return 0;
}
...
} //end of main
void answerme(){
char *answer = malloc (MAX_NAME_SZ);
while(*answer !='n' && *answer != 'N' && *answer != 'y' && *answer != 'Y'){
printf("\nPlease enter [Y], or [N]");
fgets (answer, MAX_NAME_SZ, stdin);
}
};
What the point of this while loop or the whole function is that for it to check if the user has answered the question with a y/n rather than another random key. I want this while loop to continue asking the user for a Y/N input until the user inputs it. However for some reason when this program is run, the first step asks you if you would like to begin the program, and if you do answer Y, it will for some reason tell you "please enter Y or N" even though you did enter the right answer, and then when you do enter for example "n" or even any other random letter it will still let you through. So it seems like it registers the input but for some reason it still asks runs the while loop instead of skipping to the if(answer == Y) or the if(answer ==N).
Does anyone know what could be the reason this is happening?
Also once the user says "Y" and begins the program there will be a message asking the user to input certain information and this information gets stored into a structure which I created (not shown in the code), however with this while loop, this somehow gets skipped. If I take off this while loop, the whole program works fine, but of course the user will be able to skip through steps of the program without strictly inputing what I've asked of him.
If there's any better alternative way of restricting the user into only inputing what I've asked, please do enlighten me on that as this has been causing me issues and headaches for the past 3 days. Thank you !
The problem is that you set a variable *answer in the function and there is another one in the main program. However, it looks like they are expected to be the same variable.
To fix this, declare only one and share it between the two functions. Do that by declaring it outside any function, or pass it from main to the subfunction. Note that it should be malloc() only once.
Example of the parameter passing technique is:
void answerme (char *answer)
{
while (*answer !='n' && *answer != 'N' &&
*answer != 'y' && *answer != 'Y')
{
printf ("\nPlease enter [Y], or [N]");
fgets (answer, MAX_NAME_SZ, stdin);
}
}
int main()
{
char *answer = malloc (MAX_NAME_SZ);
....
printf ("\nWould you like to begin? [Y/N]");
fgets (answer, MAX_NAME_SZ, stdin);
answerme(answer);
if (*answer == 'y' || *answer == 'Y')
{
getinfo();
printf("program starting now...\n");
}
else
if (*answer == 'n' || *answer == 'N')
{
printf("Thank you, program will close now.\n");
return 0;
}
...
} //end of main
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 10
void answerme();
int main() {
char answer[SIZE]="0";
printf ("\nWould you like to begin? [Y/N]");
scanf(" %s",answer);
if((strcmp(answer,"y")==0) || (strcmp(answer,"Y")==0))
{
printf("Answer is y\n");
printf("\nprogram starting now...");
answerme();
}
else
{
printf("Wrong input..exiting\n");
exit(1);
}
return 0;
}
void answerme()
{
char answer[SIZE]="0";
do
{
printf("\nPlease enter [Y], or [N]");
scanf(" %s",answer);
printf("You entered %s\n",answer);
}while((strncmp(answer,"y",1)!=0) && (strncmp(answer,"Y",1)!=0) && (strncmp(answer,"n",1)!=0) && (strncmp(answer,"N",1)!=0));
}

C getchar() doesn't wait for input/ conditional loop doesn't int

I am trying to add a feature to my C console application calculator that prompts the user to decide whether they want to perform another calculation using: y or n, but in testing, getchar() refuses to wait for input and the program proceeds as though it has received valid input. The following is a minimal example of the feature:
main()
{
char newCalculation;
do{
lengthFormula(); /* main calculation formula */
printf("Would you like to do another calculation? (Y/N)");
newCalculation = getchar();
}while(tolower( newCalculation ) == 'y');
if(tolower(newCalculation) == 'n'){
exitProgram(); /* exit the program */
}
while(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y'){
printf("This is not a valid response.\n Please enter \"Y\"
if you want to do another calculation,
or enter \"N\" to exit.\n");
newCalculation = getchar();
}
return 0;
}
When I run this, the program does not wait for input after:
Would you like to do another calculation? (Y/N)
, but instead proceeds as though it has received invalid input. The result is that it spits out the prompt and the invalid input notice one after the other without a space:
Would you like to do another calculation? (Y/N)
This is not a valid response.
Please enter \"Y\" if you want to do another calculation, or enter \"N\" to exit.
If I enter a "y" after this, main() returns 0 and the program terminates.
Is someone able to see where I went wrong here?
Why won't the console wait for input at getchar()?
Why does valid input terminate the program after the first invalid response?
P.S.: Please don't tell me to "read a book" or shoo me away to Dennis Ritchie or one of the previous SO discussions on input. I've been poring over Richie's discussion of I/O, as well as similar texts from Lynda.com and Wiley, and none of the previous "it won't wait for input" posts addresses my issue as far as I can tell.
#simplicisveritatis Here is the modification of your code that I tried. Still have the same getchar issues.
int main(void)
{
/* local variable declaration */
char newCalculation = 'y';
/* main function */
/*if(tolower( newCalculation ) == 'y')
{
lengthFormula(newCalculation);
}*/
do
{
lengthFormula();
printf("Would you like to do another calculation? (Y/N)");
newCalculation = getchar();
if( tolower( newCalculation ) == 'n' )
{
exitProgram();
}
while( tolower( newCalculation ) != 'n' && tolower( newCalculation ) != 'y' )
{
printf("This is not a valid response.\n Please enter \"Y\" if you want to do another calculation, or enter \"N\" to exit.\n");
newCalculation = getchar();
}
}while( tolower( newCalculation ) == 'y' );
return 0;
}
Your code has a lot of problems:
main should be:
int main(void){return 0;}
You need to cast getchar (read about getchar) and should be:
newCalculation = (char)getchar();
Your approach on do{}while; + while{} is also wrong used.
Try the following:
#include<stdio.h>
#include<stdlib.h>
int main(void){
int validate;
char menu_choice;
validate = 0;
do{
printf("Would you like another go?(y/n):\t" );
if(scanf(" %c", &menu_choice ) == 1){
if((menu_choice=='y') || (menu_choice=='Y')){
printf("You choosed Yes\n\n\n");
validate = 1;
}else if((menu_choice=='n') || (menu_choice=='N')){
printf("You choosed No\n\n\n");
validate = 2;
}else{
printf("Wrong Input.\n\n\n");
validate = 0;
}
}
}while( validate == 0 || validate == 1);
printf("Goodbye\n");
return 0;
}
Include your three cases: exit condition, wrong input and calculate within the while loop:
main(){
do{
printf("Would you like to do another calculation? (Y/N)");
// get input
char newCalculation;
newCalculation = getchar();
// exit condition
if(tolower(newCalculation) == 'n'){
exitProgram(); /* exit the program */
}
// wrong input condition
else if(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y'){
printf("This is not a valid response.\n Please enter \"Y\"
if you want to do another calculation,
or enter \"N\" to exit.\n");
// you should clear the input stream from the wrong input
}
else{
// calculate
lengthFormula();
}
}while(tolower(newCalculation) == 'y');
return 0;
}
Why won't the console wait for input at getchar()?
Most probably, your function lengthFormula() reads input (e. g. by using scanf() or whatever), but doesn't read the line ending character \n from the input buffer. Then after returning from lengthFormula(), the getchar() has to read remaining content from the input buffer rather than requesting fresh input.
Why does valid input terminate the program after the first invalid
response?
That's because your
while(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y')
does the same after a response of y as after a response of n - it leaves the loop and gets to the following
return 0;

C program crashes after char input [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am new to the C programming language and I've been trying to make a little text-based game in it. The input is very simple, as the user needs to input S or s and N or n.
The problem is, when I run the program and feed input to choice, the program simply stops working.
Here's the code:
/*O jogo */
#include <stdio.h>
#include "story.h"
int main() {
char choice;
puts(intro);
scanf("%c", &choice);
if (choice == 's' || choice == 'S') {
puts(dialog0);
puts(dialog1);
puts(dialog2);
puts(dialog3);
puts(dialog4);
puts(dialog5);
scanf(" %c", &choice);
if (choice == 's' || choice == 'S')
puts(dialog6option1);
else if (choice == 'n' || choice == 'N') {
puts(dialog6option2);
puts(dialog6option2pt2);
}
puts(dialog6);
puts(dialog7);
puts(dialog8);
puts(dialog9);
puts(dialog10);
scanf(" %c", &choice);
if (choice == 's' || choice == 'S') {
puts(dialog10option1);
puts(dialog10option1pt2);
} else if (choice == 'n' || choice == 'N') {
puts(dialog10option2);
puts(dialog10option2pt2);
}
}
return 0;
}
The program I compiled does not "stop working" (I filled in the missing strings). It simply exits when I enter 'n' at the first response, because, to summarise, it is like this.
int main() {
char choice;
puts(intro);
scanf("%c", &choice);
if (choice == 's' || choice == 'S') {
// ...
}
return 0;
}
So 'n' simply exits the program, otherwise when I start with 's' and then continue with 'n' or 's' I get the printed dialogs. Although as I commented above, what is supposed to happen when neither 'n' or 's' are entered?
BTW you have no prompts to help the user know what they are supposed to enter, or why.
The behavior of scanf is interesting especially when you include whitespace in the format string. When I wrote more console-oriented applications and wasn't using something like curses, I used a function like the following to read input:
char
get_next_input(void)
{
int ch;
while ((ch=getchar()) != EOF) {
if (!isspace(ch)) {
return (char)ch;
}
}
return (char)'\0';
}
It returns the next non-whitespace character in the stream or '\0' on EOF. I found it more reliable than using scanf across various implementations.
The problem that you are probably experiencing is line buffering on stdin. The call to scanf might not return until you press enter (e.g., enter a newline character).
You're missing a space within your first scanf:
...
puts(intro);
scanf(" %c", &choice); /* missing the space in your code*/
...

Best way of (Y/N)

I write this code:
#include <stdio.h>
#include <curses.h>
void salir (void);
int main(int argc, char** argv){
char h;
initscr();
start_color();
init_pair(1,COLOR_BLACK,COLOR_BLUE);
init_pair(3,COLOR_BLACK,COLOR_WHITE);
bkgd(COLOR_PAIR(1));
attron(COLOR_PAIR(3));
move(2,1);
printw("Welcome to my first ncurses program :D \n");
move(3,1);
printw("Would you like to read the manual? (Y/N)\n");
do{
h = getch();
if(h == 'y' || h == 'Y'){
printw("1- You must enter the numbers of rows and columns you want\n2- Then you have to specificate the type of data to enter\n");
break;
}
else if (!(h == 'n' || h == 'N')){
printw("Enter a valid option\n");
}
} while (!(h == 'n' || h=='N'));
printw("hola");
attroff(COLOR_PAIR(3));
refresh();
getch();
salir();
}
void salir(){
endwin();
exit(0);
}
My doubt is about the Y/N menu. What is the best way to do this? Also, I don't want to show the entered character in the window. It's ugly and unnecessary.
I would tend to have one key activate your menu, and any other key move on instead of only accepting 'Y' or 'N'. In other words, do a "Hit enter for menu any other key to continue" kind of thing. In code this might look like:
printw("Hit 'H' for help, any other key to continue\n");
h = getch();
if(h == 'y' || h == 'Y') {
printw("Helpful stuff here.\n");
}
printw("Getting on with our lives here, with or without help);
If you don't want the entered character to show up, you can toggle echo in ncurses with:
echo() // Turns on echo of keystrokes
noecho() // Turns off echo of keystrokes
Details on these functions available here.

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.

Resources