Yes & No answer in C - c

I am trying to make a C program where I can ask the following user yes or no questions:
Do you like beer? Y or N
Are you old enough? Y or N
How old are you?
if the user said over 18 print the message: let's go for some beers
but if one of the 2 first questions or the age is N, print: sorry maybe next time
I think the issue is with the If statement , perhaps I am not encapsulating the conditions.
#include <stdio.h>
int main(){
char answer;
int age = 0 ;
printf("Do you like beers Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n so your answer is %c\n", answer);
printf("Are you old enough to have a beer?\n");
scanf(" %c", &answer);
printf("\n so your answer is %c\n", answer);
if (answer == 'Y') {
printf("how old are you?\n");
scanf(" %d", &age);
if (age >= 18)
printf("\n Let's go for some beers , I will pay the first round \n");
}if else (age < 18 && answer == 'N')
printf("\n sorry my friend , maybe next time \n");
// printf("You may NOT ");
return 0;
}

From your code snippet above, it looks like your else statement is formatted incorrectly (if else instead of else if). Also, since you are testing whether or not either question was false, you should use the || operand. So you would want to do something like:
else if (age < 18 || answer == 'N')

The issue is your last if statement is only true if the user is under 18 AND said No. you want it to be either or.
Change the last if statement from
if else (age < 18 && answer == 'N')
To:
if else (age < 18 || answer == 'N')

You are using the same variable "answer". So, when you enter the answer to the second question it replace the first answer.
int main(){
char answer;
char answer2;
int age = 0 ;
printf("Do you like beers Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n so you answer is %c\n", answer);
printf("Are you older enough to have a beer?\n");
scanf(" %c", &answer2);
printf("\n so you answer is also %c\n", answer2);
if (answer == 'Y' && answer2 == 'Y') {
printf("how old are yo.\n");
scanf(" %d", &age);
if (age >= 18)
printf("\n lets go for some beers , I will paid the first round \n");
}
else if (answer == 'N' || answer2 == 'N')
printf("\n sorry my friend , maybe next time \n");
// printf("You may NOT ");
return 0;
}
Hope this is what you needed. Cheers.

I think that you can think that the structure of your program is roughly as follows.
REPLY = PROMPT(Q1_MESSAGE)
IF(REPLY == YES){
//Narrow down the conditions
REPLY = PROMPT(Q2_MESSAGE)
IF(REPLY == YES){
//Narrow down the conditions
REPLY = PROMPT(Q3_MESSAGE)
IF(REPLY >= 18){
DISPLAY(GOOD_MESSAGE)
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
A nested IF can be considered as AND condition as a condition.
So by summarizing the question message and its response part into a function, it is possible to write as follows.
IF(FUNC1() == TRUE AND FUNC2() == TRUE AND FUNC3() == TRUE){//Function call proceeds from left to right (Shortcut evaluated)
DISPLAY(GOOD_MESSAGE)
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
As an example, you can write concretely as follows.
#include <stdio.h>
int main(void){
char YN(const char *prompt);
int enter_age(const char *prompt);
if(YN("Do you like beers Enter Y or N: \n") == 'Y' &&
YN("Are you old enough to have a beer?\n") == 'Y' &&
enter_age("How old are you?\n") >= 20){
printf("\nLet's go for some beers, I will take the first round.\n");
} else {
printf("\nSorry my friend, maybe next time.\n");
}
return 0;
}
char YN(const char *prompt){
char ans[2], ret, ch;
int ret_scnf;
while(1){
fputs(prompt, stdout);
if((ret_scnf = scanf(" %1[YNyn]%c", ans, &ch)) == 2 && ch == '\n'){
if(*ans == 'Y' || *ans == 'y'){
ret = 'Y';
break;
} else if(*ans == 'N' || *ans == 'n'){
ret = 'N';
break;
}
} else if(ret_scnf == EOF){
ret = 'N';
break;
}
scanf("%*[^\n]");scanf("%*c");//clear input
}
return ret;
}
int enter_age(const char *prompt){
int ret_scnf, age;
char ch;
while(1){
fputs(prompt, stdout);
if((ret_scnf = scanf("%d%c", &age, &ch)) == 2 && ch == '\n'){
if(age < 0)//Can I enter years old at the age of 0?
continue;
return age;
} else if(ret_scnf == EOF){
age = -1;
break;
}
scanf("%*[^\n]");scanf("%*c");
}
return age;
}

Related

Why do I keep gettting an first use of this function error even though I wrote char answer at the top?

I tried every single solution I have found to fix that problem but non helped me. I also tried without do-while, with while (true) but couldn't make it either. My error:
error: ‘answer’ undeclared (first use in this function)
30 | }while (answer == 'n' || answer == 'N');
| ^~~~~~
.
#include <stdio.h>
int main ()
{
do {
double length;
char unit;
char answer;
printf("Enter the length: ");
scanf("%lf%c", &length, &unit);
if (unit == 'i' || unit == 'I')
{
printf("%1.2lf i = %lf c \n", length, 2.54*length);
}
else if (unit == 'm' || unit == 'M')
{
printf("%1.2lf i = %lf c \n", 39.3701*length, 100*length);
}
else if (unit == 'c' || unit == 'C')
{
printf("%1.2lf i = %lf c \n", length/2.54, length);
}
else
{
printf("0 i = 0 c");
}
printf("Do you want to start over? y/n \n");
scanf("%c", & answer);
answer = getchar();
}while (answer == 'n' || answer == 'N');
return 1;
}
char answer; is inside the do { ... } while(); loop and the scope is restricted to inside the curly brackets. You therefore cannot access answer in while() condition. which is outside the curly brackets.

Simple C program using If statement stops running in VS Code

I made a simple C program to understand the working of the If-Else statement but in VS Code the program stops at second input without any error prompt. Please tell me what's the problem with my program? I'm a beginner in programming.
#include <stdio.h>
int main(){
char math, sci;
printf("Have you passed Mathematics test (y/n)\n");
scanf("%c", &math);
printf("Have you passed Science test (y/n)\n");
scanf("%c", &sci);
if ((math == 'y') && (sci == 'y'))
{
printf("You get a gift of worth Rs. 45.");
}
else if ((math == 'n') && (sci == 'y'))
{
printf("You get a gift of worth Rs. 15.");
}
else if ((math == 'y') && (sci == 'n'))
{
printf("You get a gift of worth Rs. 15.");
}
else if ((math == 'n') && (sci == 'n'))
{
printf("You don't get any gift.");
}
return 0;
}
The second scanf() reads the newline that was left pending in stdin by the first scanf().
Use scanf(" %c", &sci); with an initial space in the conversion string to consume any newlines and initial white space in the input. Also test the return value of scanf() to detect premature end of file.
Here is modified version:
#include <stdio.h>
int main() {
char math, sci;
printf("Have you passed Mathematics test (y/n)\n");
if (scanf(" %c", &math) != 1) {
printf("Missing input\n");
return 1;
}
printf("Have you passed Science test (y/n)\n");
if (scanf(" %c", &sci) != 1) {
printf("Missing input\n");
return 1;
}
if ((math == 'y') && (sci == 'y')) {
printf("You get a gift of worth Rs. 45.\n");
} else
if ((math == 'n') && (sci == 'y')) {
printf("You get a gift of worth Rs. 15.\n");
} else
if ((math == 'y') && (sci == 'n')) {
printf("You get a gift of worth Rs. 15.\n");
} else
if ((math == 'n') && (sci == 'n')) {
printf("You don't get any gift.\n");
} else {
printf("Invalid input.\n");
}
return 0;
}
You just change
scanf("%c", &math) to scanf(" %c", &sci)
scanf("%c", &sci) to scanf(" %c", &math)
#include <stdio.h>
int main(){
char math, sci;
printf("Have you passed Mathematics test (y/n)\n");
scanf(" %c", &math);
printf("Have you passed Science test (y/n)\n");
scanf(" %c", &sci);
if ((math == 'y') && (sci == 'y'))
{
printf("You get a gift of worth Rs. 45.\n");
}
else if ((math == 'n') && (sci == 'y')||(math == 'y') && (sci == 'n'))
{
printf("You get a gift of worth Rs. 15.\n");
}
else if ((math == 'n') && (sci == 'n'))
{
printf("You don't get any gift.\n");
}
return 0;
}

How to use conditions with numbers and words

I've been trying to make this simple program that basically a little conversation. The biggest problem I've run into is that whenever I wanted to ask for the age and if someone wrongly answered with something that it's not a number, but a phrase or a word, instead of it beeing impossible it just assume a value. What can I write so that if someone rights something that is not a number it just repeats the loop?
main (){
printf("Can you tell me your age\n");
scanf("%d",&age );
do{
if ( age < 16) {
printf("You're a child!\n");
}
else if ( age == 17){
printf("Me too, cool! Let's meet.\n");
}
else {
printf("Pretty old! You are dying.\n");
}
} while ((age<=0) && (age>130));
}
To check if a character represents a digit or not, you can use the standard function isdigit().
But in your case with scanf() you can just check for its return value.
You might want to "clean stdin" if you don't know what the user will type.
void clean_stdin(void)
{
int c = 0;
while (c != '\n' && c != EOF)
c = getchar();
}
int main(void)
{
int age;
int scanf_ret;
do
{
printf("Can you tell me your age\n");
scanf_ret = scanf("%d", &age);
clean_stdin();
} while (scanf_ret != 1);
/*
Now we know that age contains a valid number
*/
return (0);
}
On success, scanf() returns the number of items of the argument list successfully filled. We've got only one argument, so we can use this return value in the while loop to continually check it against 1 (a valid input):
#include <stdio.h>
int main() {
int age, temp, status;
printf("Can you tell me your age\n");
status = scanf("%d", &age);
while(status!=1) {
while( (temp=getchar()) != EOF && temp != '\n' ) {};
printf("Invalid input... please enter a number: ");
status = scanf("%d", &age);
}
if ( age < 16) {
printf("You're a child!\n");
}
else if ( age == 17) {
printf("Me too, cool! Let's meet.\n");
}
else {
printf("Pretty old! You are dying.\n");
}
}
Hope this helps.
You need to check what scanf is returning in the if statement,you can modify you code like this:
int main()
{
int age;
printf("Can you tell me your age\n");
scan:
if((scanf("%d",&age ))==1)
{
do{
if ( age < 16) {
printf("You're a child!\n");
}
else if ( age == 17){
printf("Me too, cool! Let's meet.\n");
}
else {
printf("Pretty old! You are dying.\n");
}
} while ((age<=0) && (age>130));
}
else
{
printf("Please enter a number\n");
fflush(stdin);
goto scan;
}
return 0;
}

scanf and the char variable don't get a long [duplicate]

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;
}
}

Run-Time Check Failure #2 - s (C language on Microsoft Visual C++ 2015 (community version))

I have faced this problem : Run-Time Check Failure #2 - S in visual studio 15 . This happen before where I also trying to use array in C language. According to my textbook, what happen to the below code is
char myname[20];
printf("Type your name:");
scanf("%19s", myname);
printf("\n\n%s,Welcome to the class\n", myname);
According to the textbook, if I input my name as for example : Tony Stark, the problem will only scan the Tony and ignore all the thing after the blank space. However, when I try it, it appear Run-Time Check Failure #2.
Also in below code
#include<stdio.h>
int main(void)
{
char name[30];
int seat[30] = { 0 };
int i, seatt, j;
char decision[1];
do
{
printf("Hi, what is your name? ");
scanf("%s", name);
printf("Welcome %s!\n\n", name);
printf("*********************\n");
printf("CINEMA 1 SEATING PLAN\n");
printf("*********************");
for ( i = 0; i < 30; i++)
{
if (i % 5 == 0)
{
printf("\n\n");
}
if (seat[i] == 0)
{
printf("%3d", i);
}
else
{
printf("%3s", "**");
}
}
printf("\n\n*********************");
do
{
printf("\n\nWhich seat do you want? ");
scanf("%d", &seatt);
if (seat[seatt]!=0)
{
printf("Sorry, seat is taken!\n");
for ( j = 0; j < 30; j++)
{
if (seat[j] == 0)
{
printf("Suggest to take seat: %d", j);
break;
}
}
}
} while (seat[seatt] != 0);
++seat[seatt];
printf("\n\nWould you like to make next booking (Y or N)? ");
scanf("%s", decision);
printf("\n\n");
if (decision[0] == 'Y' || decision[0] == 'y')
{
system("cls");
}
} while (decision[0] == 'Y' || decision[0] == 'y');
printf("See you again!\n");
return 0;
}
Everything is ok, until when until the last part where it ask me where to book the next ticket, if I keyin another other than Y, it also appear the same problem.
You are not very careful with respect to stack overflows. In the second code, you use:
char decision[1];
scanf("%s", decision);
The scanf will append a trailing \0 termination character already interfering with some other data on the stack even if you really only input a single character. More disaster is at hand when the user input is longer. Scan with a "%c" format in this case.
What you should do is you should scan in character instead of String
Do:
char decision[1];
scanf("%c", decision);

Resources