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;
}
Related
image
I am working on a seat reservation program and here are some of its parts. My objective is to mark 'X' on the array using the user input. This is based on a tic tac toe program but I need to mark X only in the table. I am asking if I am doing the loop for the program correctly and if not what I use to fix it. I am facing errors but I don't know if this is the right loop for them.
I want to mark X based on the input of rows and columns that they are given and if it is already entered or marked. I want to say that it is already taken and will prompt the user again if they want to enter a new input again and if not they will be returned to the main menu again.
typedef struct{
char city[20], name[50], seatcol;
int age, seatrow, id;
}passenger;
char seat[ROWS][COLS];
void reserve(){
passenger p;
do {
printf("\n\t\t\tEnter your seat number:");
printf("\n\t\t\tROW:(1-10) ");
scanf(" %d",&p.seatrow);
printf("\t\t\tCOLUMN:(A-F) ");
scanf(" %s ", p.seatcol);
if(p.seatrow == 1 && p.seatcol == 'A')(
seat[0][0]= 'X');
else if(p.seatrow == 1 && p.seatcol == 'B')(
seat[0][1]= 'X');
else if(p.seatrow == 1 && p.seatcol == 'C')(
seat[0][2]= 'X');
else if(p.seatrow == 1 && p.seatcol == 'D')(
seat[0][3]= 'X');
else if(p.seatrow == 1 && p.seatcol == 'E')(
seat[0][4]= 'X');
else if(p.seatrow == 1 && p.seatcol == 'F')(
seat[0][5]= 'X');
//2
else if(p.seatrow == 2 && p.seatcol == 'A')(
seat[1][0]= 'X');
else if(p.seatrow== 2 && p.seatcol == 'B')(
seat[1][1]= 'X');
else if(p.seatrow == 2 && p.seatcol == 'C')(
seat[1][2]= 'X');
else if(p.seatrow == 2 && p.seatcol == 'D')(
seat[1][3]= 'X');
else if(p.seatrow == 2 && p.seatcol == 'E')(
seat[1][4]= 'X');
else if(p.seatrow == 2 && p.seatcol == 'F')(
seat[1][5]= 'X');
else{
printf("Invalid option!");
p.id--;
getch();
}
p.id++;
status = (p.seatrow && p.seatcol != seat);
}while(status);
if(!status){
printf("\n\t\t Already allocate seat. Choose another seat? (Y/N)");
scanf("%s", answer);
if(answer == ' Y'){
printf("\n\t\t\tROW:(1-10) ");
scanf(" %d",&p.seatrow);
printf("\t\t\tCOLUMN:(A-F) ");
scanf(" %s ", p.seatcol);
}
else{
printf("Your data will be not saved and will be returned to main menu:");
mainmenu();
}
}
}
I am trying to get this yes no programme to work in a loop. I've checked the other users messages and there's only one which is poorly written and doesn't work properly.
So if the user types y or Y it installs and if they type n or N it exits out of the program. Also if they type w, m or any other letter that isn't y or n it goes back to the start and asks them again.
Not sure if its a while loop or a do while loop. The programme below works but doesn't have any loops.
#include <stdio.h>
int main() {
char yn;
printf("Do you want to install this programme? y/n: ");
scanf("%c", &yn);
if(yn == 'y' || yn == 'Y') {
printf("Installing...\n");
}
else if(yn == 'n' || yn == 'N') {
printf("Exiting programme!\n");
}
else {
// Go back to the start/top of the programme!
}
return 0;
}
You can wrap your code into a while-loop.
Something like:
while(1)
{
printf("Do you want to install this programme? y/n: ");
scanf("%c", &yn);
if(yn == 'y' || yn == 'Y') {
printf("Installing...\n");
break; // Stop the while-loop to end the program
}
else if(yn == 'n' || yn == 'N') {
printf("Exiting programme!\n");
break; // Stop the while-loop to end the program
}
}
The type of loop that makes most sense in this scenario is a do/while loop since getting a response from a user is something that should happen at least once and be tested for until a desired response is obtained from the user.
Also, using tolower or toupper on yn when checking for equality can eliminate the need to check both upper and lowercase.
do
{
printf("Do you want to install this program? y/n: ");
scanf(" %c", &yn);
}
while(tolower(yn) != 'n' && tolower(yn) != 'y');
if(tolower(yn) == 'n')
{
printf("Exiting program\n");
}
else
{
printf("Installing ...\n");
}
fgets can be used to capture the input. It has an advantage of being able to clear the input stream in case of too many characters or incorrect characters.
#include <stdio.h>
#include <string.h>
int main ( void) {
char input[3] = "";//can hold one char a newline and a '\0'
printf("Do you want to install this programme? y/n: ");
do {
printf ( "\nenter y or n\n:");
if ( fgets ( input, sizeof input, stdin)) {
if ( !strchr ( input, '\n')) {//is there a newline?
while ( !strchr ( input, '\n')) {//call until newline is found to clear input
if ( !fgets ( input, sizeof input, stdin)) {
fprintf ( stderr, "\nEOF problem\n");
return 1;
}
}
input[0] = 0;
printf ( "\ntoo many characters. try again.");
}
}
else {
fprintf ( stderr, "\nEOF problem\n");
return 1;
}
if ( input[0] == 'y' || input[0] == 'Y') {
printf("Installing...\n");
}
if ( input[0] == 'n' || input[0] == 'N') {
printf("Exiting programme!\n");
}
} while ( input[0] != 'y' && input[0] != 'n' && input[0] != 'Y' && input[0] != 'N');
return 0;
}
Solved!
This is the code that works. Thanks to #govindparmar.
#include <stdio.h>
int main() {
char yn;
do {
printf("Do you want to install this programme? y/n: ");
scanf(" %c", &yn);
}
while(yn != 'n' && yn != 'N' && yn != 'y' && yn != 'Y');
if(yn == 'n' || yn == 'N') {
printf("Exiting programe!\n");
}
else {
printf("Installing...\n");
}
printf("It works!\n");
return 0;
}
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;
}
Observe this chunk of code:
#include <stdio.h>
int main(void)
{
char choice;
printf("\n\nDo you want to play again (Y/N)? ");
scanf(" %c", &choice);
if (choice != 'Y' || choice != 'y' || choice != 'N' || choice != 'n')
{
printf("\n\nYou didn\'t enter a decision.");
}
return 0;
}
I want the printf() to prompt the user to input either Y or N. The scanf() will fill the user's input in the variable choice. If choice is not equal to Y, y, N, or n, it will tell the user that he/she didn't enter a decision. Then, the program will end.
However, when I inputted Y or N, it printed "You didn't enter a decision." This should only happen if I don't enter Y or N (lowercase or uppercase).
I even put a space before the conversion character so the scanf() wouldn't read the newline character (\n).
Any help would be greatly appreciated!
Change
if (choice != 'Y' || choice != 'y' || choice != 'N' || choice != 'n')
to
if (choice != 'Y' && choice != 'y' && choice != 'N' && choice != 'n')
otherwise whether you enter any of Y, y, N, n or any other character (as pointed by Jonathan Leffler in the comment), the expression in if will be evaluated to true.
You Have to Just Include Else Like Following
#include <stdio.h>
int main(void)
{
char choice;
printf("\n\nDo you want to play again (Y/N)? ");
scanf(" %c", &choice);
if (choice != 'Y' || choice != 'y' || choice != 'N' || choice != 'n')
{
printf("\n\nYou didn\'t enter a decision.");
}
return 0;
}
Please help, I cant seem to get the do-while loop to loop when I ask the user to input continue using scanf and printf. Could it be the wipe_buffer? I can't seem to get it right on this and I just need to finish the loop and that should be mostly functional. New to coding and this website please not too harsh. please and thanks.
#include <stdio.h>
#include <stdlib.h>
void wipe_buffer(void);
int main(int argc, char* argv[])
{
char play1;
char play2;
char cont;
do{
printf("Player one pick Rock, Paper, or Scissors\n");
scanf(" %c", &play1);
wipe_buffer();
printf("Player two pick Rock, Paper, or Scissors\n");
scanf(" %c", &play2);
wipe_buffer();
switch(play1)
{
case 'r':
if(play2 == 'p' || play2 == 'P')
{
printf("Paper Covers Rock\n");
printf("Player two wins\n");
}
if(play2 == 's' || play2 == 'S')
{
printf("Rock Breaks Scissors\n");
printf("Player one wins\n");
}
if(play2 == 'r' || play2 == 'R')
{
printf("Draw, Nobody wins\n");
}
break;
case 'R':
if(play2 == 'p' || play2 == 'P')
{
printf("Paper Covers Rock\n");
printf("Player two wins\n");
}
if(play2 == 's' || play2 == 'S')
{
printf("Rock Breaks Scissors\n");
printf("Player one wins\n");
}
if(play2 == 'r' || play2 == 'R')
{
printf("Draw, Nobody wins\n");
}
break;
case 'P':
if(play2 == 'p' || play2 == 'P')
{
printf("Draw, Nobody wins\n");
}
if(play2 == 's' || play2 == 'S')
{
printf("Scissors cuts Paper\n");
printf("Player two wins\n");
}
if(play2 == 'r' || play2 == 'R')
{
printf("Paper covers rock\n");
}
break;
case 'p':
if(play2 == 'p' || play2 == 'P')
{
printf("Draw, Nobody wins\n");
}
if(play2 == 's' || play2 == 'S')
{
printf("Scissors cuts Paper\n");
printf("Player two wins\n");
}
if(play2 == 'r' || play2 == 'R')
{
printf("Paper covers rock\n");
}
break;
case 's':
if(play2 == 'p' || play2 == 'P')
{
printf("Scissors Cuts Paper\n");
printf("Player one wins\n");
}
if(play2 == 's' || play2 == 'S')
{
printf("Draw, Nobody wins\n");
}
if(play2 == 'r' || play2 == 'R')
{
printf("Rock breaks Scissors\n");
printf("Player two wins\n");
}
break;
case 'S':
if(play2 == 'p' || play2 == 'P')
{
printf("Scissors Cuts Paper\n");
printf("Player one wins\n");
}
if(play2 == 's' || play2 == 'S')
{
printf("Draw, Nobody wins\n");
}
if(play2 == 'r' || play2 == 'R')
{
printf("Rock breaks Scissors\n");
printf("Player two wins\n");
}
break;
}
printf("Do you wish to continue?\n");
scanf(" &c", &cont);
wipe_buffer();
}while(cont == 'y' || cont == 'Y');
}
void wipe_buffer(void)
{
char t;
scanf("%c", &t);
while(t != '\n' )
{
scanf("%c", &t);
}
return;
}
In this section:
printf("Do you wish to continue?\n");
scanf(" &c", &cont);
"&c" should be "%c"
Note that when I compiled this with gcc, I got a warning that basically addressed this exact problem, so make sure to read your warnings.
In here:
printf("Do you wish to continue?\n");
scanf(" &c", &cont);
wipe_buffer();
}while(cont == 'y' || cont == 'Y');
there should be:
scanf(" %c", &cont);
Compile with -Wall -pedantic options next time you face some problem(if you use gcc).
It shows nicely where the problem lies, and if not - it narrows it down a little.
That's what it shows in your case:
test2.c:117:5: warning: too many arguments for format [-Wformat-extra-args]
test2.c:120:1: warning: control reaches end of non-void function [-Wreturn-type]
so it's also a nice reminder that your main() function has to return some value.
Another suggestion is to rad through this link:http://www.gidnetwork.com/b-60.html
and follow to The Steps page.
To make it short - there's some information on how time and space consuming is reading one char from stdin with scanf in comparison to getchar.
Consider applying this suggestion in your code.
So, a really quick way to see what's going on is to drop a debugging printf statement right before the loop
scanf(" &c", &cont);
wipe_buffer();
printf("Debug: [%c]\n", cont);
}while(cont == 'y' || cont == 'Y');
Then look for the printf when the program runs.
I think what is going on is that each scanf is looking for a Enter keystroke before processing, so wipe_buffer is going to request a lot of Enter keystrokes before continuing. Try running the program without the wipe_buffer and you'll still need to press Enter before it continues.