This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
I just started coding so sorry for the stupid question. This is C programming.
When the user inputs Y, the code runs as intended. If the user inputs N or any other character, the program loops but it repeats the same line twice for some reason.
For example:
Input: Y
Output: The game will now start!
Input: N
Output: Waiting...
Would you like to start the game? <Y/N>:
is not a valid response
Would you like to start the game? <Y/N>:
As you can see the line doubles, how do I fix this?
do {
printf("Would you like to start the game? <Y/N>: ");
scanf("%c", &cGameStart);
if (cGameStart == 'Y')
printf("\nThe game will now start!\n");
if (cGameStart == 'N')
printf("\nWaiting...\n\n");
if ((cGameStart != 'Y') && (cGameStart != 'N'))
printf("%c is not a valid response\n", cGameStart);
} while (!(cGameStart == 'Y'));
The comment are rather irrelevant to the problem.
The problem is the \n character left in the buffer by scanf. Eat it and it will work as intended.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char cGameStart;
do {
printf("Would you like to start the game? <Y/N>: ");
scanf("%c", &cGameStart);
if (cGameStart == 'Y')
printf("\nThe game will now start!\n");
if (cGameStart == 'N')
printf("\nWaiting...\n\n");
if ((cGameStart != 'Y') && (cGameStart != 'N'))
printf("%c is not a valid response\n", cGameStart);
fgetc(stdin);
} while (!(cGameStart == 'Y'));
printf("Game started\n");
}
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
How to do scanf for single char in C [duplicate]
(11 answers)
Closed last year.
I was trying to build the game of rock paper scissors in C. When I made it for playing one single time, it was working properly. But when I tried to make it run for multiple number of times using for loop, it failed to scan the value given by the user. It is running the code correctly when it is the eventh turn, i.e , 2nd,4th,6th and so on. But it fails to take the input when it is odd turn.
The code is given below:
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter the number of times you want to play rock paper scissors: ");
scanf("%d", &n);
for(int i=0;i<n;i++){
char c,p;
//creating random rps generator
int num;
srand(time(0));
num=rand()%3+1;
if(num==1){
c='r';
}
else if(num==2){
c='p';
}
else{
c='s';
}
//Taking input from the user
printf("Enter rock(r),paper(p) or scissors(s) : ");
scanf("%c",&p);
//Main code
if(c==p){
printf("It's a draw.\n");
}
else if((c =='r' && p =='p') || (c =='p' && p =='s') || (c =='s' && p =='r')){
printf("You win.\n");
}
else if((c =='p' && p =='r') || (c =='s' && p =='p') || (c =='r' && p =='s')){
printf("You lose.\n");
}
}
return 0;
}
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
scanf Getting Skipped [duplicate]
(1 answer)
Closed last year.
I try to make a program that the output will be the classification based on the input grade (by character). Here is my code:
main ()
{
char choice,grade;
printf("Enter a grade: \n");
scanf("%c",&grade);
do
{
if (grade == 'a' or grade == 'A')
{
printf("Excellent!\nDo you want to continue?\n");
}
else if (grade == 'b' or grade == 'B')
{
printf("Good!\n Do you want to continue?\n");
}
else if (grade == 'c' or grade == 'C')
{
printf("Fair!\n Do you want to continue?\n");
}
else if (grade == 'd' or grade == 'D')
{
printf("Average!\n Do you want to continue?\n");
}
else if (grade == 'f' or grade == 'F')
{
printf("Weak!\n Do you want to continue?\n");
}
else
{
printf("Invalid!\n Do you want to continue?\n");
}
scanf("%c",&choice);
} while (choice == 'y');
}
And this is the outcome of the code:
enter image description here
It doesn't allow me to type yes or no. It just ends.
It would be very great if someone explain to me where I'm wrong since this is the first coding language that I learn and I am trying so hard to understand it by myself.
Your scanf() inside the do-while is getting skipped because when you press enter after inputting a grade, scanf() accepts it as a return character. So, do this instead: scanf(" %c", &grade).
I'm creating a conversion project for letters/numbers ASCII table. My code is supposed to be 'interactive', so the user would type 'y' or 'n' to answer questions on the screen. However, it doesn't want to do this twice...
I have tried:
Just trying numbers instead of characters, but it's not exactly what I want
The %[\n]*c, and %[\n]c, and %[\n]*s ... technique but it doesn't help ;-;
Testing in a different project, but the only way I am able to do it is for multiple scanf()s to be in a row.
Here is the code:
printf("Would you like to convert a number today? \n");
printf("Please press Y or N \n");
scanf("%c", &input);
if (input == 'y' || input == 'Y') { //compare input if they said 'yes'
printf("\nThank you! \nWhat number?\n");
scanf("%d", &number);
flag = test(number);
if (flag == 0) { //if there is an equivalent letter
letter = conversion(number); //find the equivalent letter
printf("\nYour Number \t ASCII letter\n");
printf("%d\t %c\n", number, letter);
}
}
else if (input == 'n' || input == 'N') {
printf("\nWould you like to convert a letter instead? This time enter 0 or 1\!\n\n"); //problem here!!
printf("I wish I could say it was to \' Spice things up \' ...but it\'s not ;-; \n\n");
scanf("%d", &input2);
if (input2 == 0) { //this needs to be checking whether the user input Y/y
printf("Great choice adventurer!\n");
printf("What letter will it be today?\n\n");
//..I would go to a different funtion here ie: test2(letter)...
scanf("%d", &number); //I showed that it worked with multiple numbers, but I can't get this to work with multiple letters
printf("%d", number);
}
if (input2 == 1) { //this needs to be checking whether the user input N/n
printf("Difficult to please, I see...\n\n");
printf("I suggest you move on with that attitude!\n\n");
printf("Bye bye then\n");
}
}
else { //if they tried to break the code
printf("Sorry I did not recognise your command...please retry\n");
printf("Press Y or N next time!\n");
}
The first check works perfectly, I just want the second check to be like the first!
Some 'solutions' caused a overflow, which I don't want if possible
Even if someone could explain why this isn't working the way I intended would be very helpful!
I'm not sure what confuses you.
Use
char foo;
scanf(" %c", &foo);
for single characters, eg. letters and
int bar;
scanf("%d", &bar);
for numbers, integers. If you type a letter instead, scanf() will fail.
%[...] is for strings.
scanf() returns the number of successful conversions (or EOF), so for
int height;
int width;
scanf("%d %d", &height, &width);
it returns 2 if successful. It might return 1 if only height could be read.
So to check for errors on user input you should do:
int height;
int width;
if (scanf("%d %d", &height, &width) != 2) {
// handle the error, maybe exit the program.
}
Your code could look like that (without error handling):
#define _CRT_SECURE_NO_WARNINGS // you said Visual Studio? Without it you should get
// warnings about some functions being insecure.
#include <ctype.h> // isalpha() returns true if the value is a letter
#include <stdlib.h> // EXIT_SUCCESS
#include <stdio.h> // puts(), printf(), scanf()
int main(void)
{
for(;;) { // for-ever ... endless loop since the user exits by answering
// 'n' or 'N' two times
puts("Would you like to convert a number today?\nPlease press Y or N:");
char input;
if (scanf(" %c", &input) != 1) // We reached EOF ... end of file
break; // that's improbable for stdin,
// but input could be redirected to
// read from a file instead.
if (input == 'y' || input == 'Y') {
puts("\nThank you!\nWhat number?");
int number;
scanf("%d", &number);
if (isalpha((char unsigned)number)) // *)
printf("\nYour Number \t ASCII letter\n%d\t %c\n\n", number, number);
else
puts("Sorry, but that's not the ASCII code of a letter :(\n");
}
else if (input == 'n' || input == 'N') {
puts("\nWould you like to convert a letter instead?\nPlease press Y or N:");
scanf(" %c", &input);
if (input == 'y' || input == 'Y') {
puts("\nGreat choice adventurer!\nWhat letter will it be today?");
char letter;
scanf(" %c", &letter);
if (isalpha(letter))
printf("\nYour letter \t ASCII code\n%d\t %c\n\n", letter, letter);
else
puts("Sorry, but that's not a letter :(\n");
}
else if (input == 'n' || input == 'N') {
puts("\nDifficult to please, I see...\n\nI suggest you move on with that attitude!\n");
puts("Bye bye then.");
return EXIT_SUCCESS;
}
}
else {
puts("Sorry I did not recognize your command... Please retry.");
puts("Press Y or N next time!\n");
}
}
}
*) isalpha() (and the other functions in <ctype.h>) expects a value that fits in a unsigned char or the value EOF. It has undefined behaviour for other values. Since we read user input into an int we cannot be sure that's the case so we have to cast the value to unsigned char before passing it to isalpha() (and friends).
Next time you ask a question please include your full code, including variable declarations, functions like test() and conversion() and #includes. But please, post an example that focuses on your problem at hand. All that dialog you included would not have been necessary.
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 years ago.
#include <stdio.h>
#include <conio.h>
void main(){
int turn,i=1,num;
char answer;
for(i>0;i++;){
printf("Please enter a number in the range 1-5:");
scanf("%d",&num);
if (num == 1){
printf("Disconnecting\n");
continue;
}
else if(num == 2){
continue;
}
else if(num == 3){
printf("Are you sure you would like to finish your order??? \nplease enter one char:");
scanf("%c", &answer);
if(answer == 'y'){
printf("Canceled");
break;
}
else{
continue;
}
}
else if(num == 4){
turn=i-1;
printf("your position in queue is:%d\n",turn);
continue;
}
else if(num == 5){
break;
}
else {
printf("Wrong input\n");
continue;
}
}
getch();
}
I'm using c language for this,
if You look at the
else if(num == 3)
it should function in a way that when I enter the letter y,Y it will say canceled and end the program and if not it will just reset the loop.
now when I use the number 3 and give the variable c the letter 'y'
it just says nothing and acts like I gave it the command "continue" + pressed the number 3 again although all I have done is press y or Y and enter.
everything else is good.
I would be glad if anyone can tell me how to fix that.
for(i>0;i++;){
printf("Please enter a number in the range 1-5:");
scanf("%d",&num);getchar();
//... rest of your code
}
use getchar or getch to consume extra newline character
The getch found at the bottom of your main is being used to get order numbers.
Try putting a "getch" in right before you are looking for your y character.
That is to say, something like:
else if(num == 3){
printf("Are you sure you would like to finish your order??? \nplease enter one char:");
getch();
scanf("%c", &answer);
if((answer == 'y') || (answer == 'Y')) {
printf("Canceled");
exit;
} else {
continue;
}
}
I've been trying to get this code to work but the loop does not seem to work? I am very new to C and I sort of get confused with the syntax of this language. However my loop is not functioning like how I want it to be. I want the if and else statement to work but no matter what input (right or wrong) it always outputs "thank you".
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c = 'Y' && 'y' && 'N' && 'n')
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}
int main(int argc, char* agrv[])
{
confirm();
return 0;
}
it won't ask to enter another output when the output is incorrect. It just keeps ending from the if statement, thus the loop is not running?
Please help.
There's nothing wrong with your loop - it's the if statement that's wrong.
This code compiles, but it does not do what you want it to do:
if (c = 'Y' && 'y' && 'N' && 'n')
= is an assignment; you need == to do a comparison
&& means "AND"; you need ||, which means an "OR"
You combine logical expressions, not constants with && or ||
The condition should be
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
Also note that when you read single characters with %c, your program "sees" all characters, including whitespace. This is a problem, because the '\n' left over in the buffer will be passed to your program before Y or N. To fix this, add a space before %c to your format string:
scanf(" %c", &c)
// ^
// |
// Here
Your code also ignores the first character that it reads. I think this is not intentional, so remove the call of scanf before the loop. You should also remove the second scanf from the loop, leaving the only call to scanf in the loop header.
int confirm()
{
char c;
printf("Confirm (y/n): ");
//scanf("%c", &c);// <---------- needless
while (scanf("%c", &c)) //<----while loop will do `scanf("%c",&c)`, so previous line should be remove.
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')// <- &&(AND); ||(OR). Also, be careful that don't be lazy, [c == 'Y' || 'y' || 'N' || 'n'] can't to communicate with computer
{
printf("\nthank you");
break;
}
else
{
printf("\nInput not recognised, try again. \n");
printf("\nConfirm (y/n): ");
scanf("%c", &c);
}
}
}