Yes/No loop in C - c

I just don't understand why this Yes/No loop will not work. Any suggestions? Given the input is "Y". I just want it to run the loop, then ask for Y or N again. If Y, print success, if N, print a good bye statement. What's the reason?
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n", answer);
scanf("%c", &answer);
printf("\n answer is %c");
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf("%c", &answer);
}
printf("GoodBye!");
return 0;
}

Change the second scanf to:
scanf(" %c", &answer);
// ^
The problem is, when you enter Y and press ENTER, the new line is still in the input buffer, adding a space before %c could consume it.

fixed the various issues
#include <stdio.h>
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
}
printf("GoodBye!");
return 0;
}

You can reduce the repetition in your code a bit, and check the result of scanf() (as you should) by writing:
int main(void)
{
char answer;
printf("Would you like to play? Enter Y or N: ");
while (scanf(" %c", &answer) == 1 && answer == 'Y')
{
printf("Answer is %c\n", answer);
printf("Success!\n");
printf("Do you want to play again? Y or N: ");
}
printf("GoodBye!\n");
return 0;
}
The first printf() lost the unused argument answer; the second printf() collected the necessary second argument, answer. Except for prompts, it is generally best to end printing operations with a newline (rather than use a newline at the start). Prompts will generally be flushed by the C library before the input from stdin is read, so you don't need the newline at the end of those.
Since printf() returns the number of characters it prints, you can use it in conditions too:
int main(void)
{
char answer;
printf("Would you like to play? Enter Y or N: ");
while (scanf(" %c", &answer) == 1 &&
printf("Answer is %c\n", answer) > 0 &&
answer == 'Y')
{
printf("Success!\n");
printf("Do you want to play again? Y or N: ");
}
printf("GoodBye!\n");
return 0;
}
This always echoes the answer, even if the answer was not Y and the loop exits.

Related

One more question about using a while to "embrace" my code instead of calling main()

So, in this link -> Problems doing a while loop I did a question about a problem dealing with the use of while instead of calling main(), and it helped me, my code worked, but there's a new little problem. I'mma show it with a kind of "Dice Roller Code"
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
srand((unsigned)time(NULL));
int totalSides, dice, modifier;
char c, d;
printf("Welcome to the dice roller!\n");
printf("If you wanna roll the dice, press 'r'. If you wanna quit, press 'q': ");
scanf(" %c", &c);
while(c == 'r'){
printf("How many sides does the dice you want to roll have? Answer with a int number: ");
scanf("%d", &totalSides);
printf("Do you need any modifier? Press 'a' to add, press any other key to dispense: ");
scanf(" %c", &d);
if(d == 'a'){
printf("Insert your modifier value: ");
scanf("%d", &modifier);
printf("\n");
}
dice = rand() % totalSides + 1;
printf("You've got a %d!\n", dice);
if(d == 'a'){
printf("But you've got a %d modifier...\n", modifier);
dice = dice + modifier;
printf("Then, you got a %d!", dice);
}
printf("\n\n\n\n");
repeat();
c = repeat();
printf("\n\n\n\n");
}
}
int repeat(){
char c;
printf("Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: ");
scanf("%c", &c);
return c;
}
The program works very well, but in the output I got the same sentence two times, like:
"Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: "
How can I solve this?
You are calling repeat twice, so therefore it is printing twice.
repeat();
c = repeat();
Try replacing the first call to repeat to getchar(). This will consume the character entered after the modifer line.
getchar();
c = repeat();
It looks like you are just starting to learn C, and it might be worthwhile to read a book on the matter. One that I can recommend is Modern C. It's available free online, or you can buy a print version.

if statement with char condition in C

I have been working on a college project. I want user to enter Y/N if he wants to continue or not, so I wrote following code
repeat:
pr=0;
q=0;
res=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf("%d",&res);
if(res=='y')
goto repeat;
else
return 0;
}
The problem is entering y executes else statement. I tried replacing y with 1,2,3.... and it works but I want it to work with Y or y or yes.
There is a bug in this line
scanf("%d",&res);
It should be
scanf(" %c",&res);
The formatting placeholders for char is %c not %d
scanf("%d",&res);
should be
scanf(" %c",&res);
As suggested by multiple users do while should be used over goto, so better code would be
do{
pr=0;
q=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf(" %c",&res);
}
while(*res == 'Y' || *res == 'y');
return 0;
}
Also res should also be declared char res;

How to loop a whole codeblock in C?

So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)

C uninitialized local variable error

New to C still learning.
The program should start the first time with out needing to be asked to do anything. Then it prompts the user to continue with a "Y/N". I keep errors could anyone tell me why it doesn't work I don't know what to do with the errors that I get from it.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
void theQnA(char charIn);
int main(void)
{
int answerint = 0;
char charIn;
char anwser;
printf("Enter a character to be examined: ");
scanf("%c", &charIn);
theQnA(charIn);
while (answerint == 0)
{
printf("Would you like to run it again? Y/N\n");
scanf("%c", &anwser);
if (anwser == 'y')
{
printf("Enter in another character buddy\n");
scanf("%c", &charIn);
theQnA(charIn);
}
else (anwser != 'y')
{
answerint = (answerint--);
}
}
printf("Goodbye\n");
return 0;
}
void theQnA(char charIn)
{
if (islower(charIn))
printf("You have entered in a lower case letter dude\n");
else if (isdigit(charIn))
printf("You enterd in a num man\n");
else if (isupper(charIn))
printf("Its upper case man\n");
else if (ispunct(charIn))
printf("You entered in a punctuation!\n");
else if (isspace(charIn))
printf("You enterd in a whitespace dude\n");
else
printf("control char/n");
return;
}
You have else (anwser != 'y'). It should be else if (anwser != 'y'), or better yet just else. The prompt Would you like to run it again? Y/N will also be printed twice because of how your loop is structured. You have quite a few mistakes, but here's some advice on your loop.
You can use your anwser variable in your while condition. answerint is unnecessary. Also, when you type a character and press enter, scanf (with %c) will extract the character but leave the newline in the buffer. That means the next call to scanf will return a newline, which will make it appear as if your program is skipping your input statements. To fix this, add a space before the %c in your call:
scanf(" %c", &charIn);
Your logic was also a bit out of place. Look at how this example is structured.
printf("Enter a character to be examined: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
while (anwser == 'y')
{
printf("Enter in another character buddy: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
}

scanf won't ask for input the second time [duplicate]

This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
The output looks like this
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
The second input was skipped. Why?
because of newline character already in stdin , this is happening.
use
scanf(" %c", &cont);
instead of
scanf("%c", &cont);
note one space before %c.
After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.
Another answer to this can be found here:
scanf() leaves the new line char in buffer?
This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.
For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.
Instead, use getchar() for all your input and check for \n
For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:
C - trying to read a single char
This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.
You can use fflush()
printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);

Resources