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*/
...
Related
I am trying to write a program in C where I intend to control the execution of a while loop according to user input in stdin. I am able to write the program in three different ways as following which perform as intended:
Using scanf() function
#include<stdio.h>
#include<string.h>
int main()
{
char loop= 'y';
while(loop=='y')
{
printf("Do you want to continue? [y|n]: ");
scanf("%c", &loop);
while(getchar() != '\n');
if(loop != 'y' && loop != 'n')
{
printf("Error! Please enter 'y' or 'n' \n");
loop = 'y';
}
}
return 0;
}
Using fgets() function
#include<stdio.h>
#include<string.h>
int main()
{
char loop[5]= "yes\n";
printf("%s",loop);
while(strcmp(loop,"yes\n")==0)
{
printf("Do you want to continue? [yes|no]: ");
if(strcmp(loop,"yes\n")!=0 && strcmp(loop,"no\n")!=0)
printf("Error! Please Enter 'yes' or 'no'\n");
else
fgets(loop,5,stdin);
}
return 0;
}
Using getch() from conio.h
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char loop= 'y';
while(loop=='y')
{
printf("Do you want to continue? [y|n]: ");
loop = getch();
printf("\n");
if(loop != 'y' && loop != 'n')
{
printf("Error! Please enter 'y' or 'n' \n");
loop = 'y';
}
}
return 0;
}
Although all the aforementioned methods perform the task of stopping or continuing the while loop according to user input, the getch() is little different. Using getch(), the user does not have to press the enter after the user inputs y or n and the program terminates or continues as soon as the user provides input.
I am aware that conio.h is not included in the standard gcc library and is frowned upon to use. However, I would like to implement the functionality of getch() using either scanf() or fgets() or any other standard library function. By functionality of getch(), I mean that as soon as a user press the desired key on terminal, the while loop should terminate without needing to press the enter by the user.
Is it possible for either fgets() or scanf() to do this task?
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));
}
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
Given a int variable named yesCount and another int variable named noCount and a char variable named response, write the necessary code to read a value into into response and then carry out the following:
if the character typed in is a y or a Y then increment yesCount and print out "YES WAS RECORDED"
if the character typed in is an n or an N then increment noCount and print out "NO WAS RECORDED"
if the input is invalid just print the message "INVALID" and do nothing else.
Hello, I am having trouble with my C code for this problem. I'm getting incorrect outputs. Any assistance is much appreciated. Thank you.
if (response == 'y' || response == 'Y') {
scanf("%d", &yesCount);
yesCount++;
printf("YES WAS RECORDED");
}
if (response == 'n' || response == 'N') {
scanf("%d", &noCount);
noCount++;
printf("NO WAS RECORDED");
} else {
printf("INVALID");
}
There might be some typo here because I'm writing from my smartphone. Be aware of that. By the way here as how I would do that :
#include <stdio.h>
int main(void) {
int yescount = 0, nocount = 0;
int c;
while ((c = getchar) != EOF) {
switch (c) {
case 'y':
case 'Y':
puts("Yes registered");
yescount++;
break;
case 'n':
case 'N':
puts("No registered");
nocount++;
break;
default:
puts("Invalid selection.");
break;
}
}
return 0;
}
You should learn how to present your code correctly: it helps a lot with readability and makes many bugs more visible.
There are problems with your code:
You call scanf for no purpose, but you do not read the response as requested.
You forgot an else at the end of the body of the first if. The consequence is that the last else branch is taken if the response is y or Y.
You should probably print a \n after each message so it appears separate from the subsequent output.
Here is a corrected version:
scanf("%c", &response);
if (response == 'y' || response == 'Y') {
yesCount++;
printf("YES WAS RECORDED\n");
} else
if (response == 'n' || response == 'N') {
noCount++;
printf("NO WAS RECORDED\n");
} else {
printf("INVALID\n");
}
From your comment, they expect you to use scanf("%c", &response); to read the char into response, not the simplest way to read a byte from stdin.
I have a problem with my input for my program:
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
{
printf("\nThank you. \n");
break;
}
else
{
printf("\nInput not recognised, ry again. \n");
printf("Confirm (y/n): ");
}
}
}
int main(int argc, char* argv[])
{
confirm();
return 0;
}
When it executes, it asks the first question and inputting the answer is fine. However after entering the character (either y or n) the program prints the second question and stops. The whole program is not running. I don't know what I'm doing wrong.
Loose the first scanf at line 9 and (for me) it then seem to work correctly: if ynYN is entered then the confirm function exits, otherwise it continues looping
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.