This question already has answers here:
Most efficient way to compare a variable to multiple values?
(7 answers)
Closed last year.
I have been struggling to get my if statement in my function to evaluate correctly. I am attempting to get the if statement to evaluate as true only if the variable is equal to 'Y' or 'y'. I am new to messing with char variables, so my suspicion is I am either storing chars into the variable incorrectly, or evaluating the expression in a way that is always true.
The code I wrote is the following:
#include <stdio.h>
// fuctions
int Greeting(void);
// variables
int return_status;
int main(void)
{
return_status = Greeting();
printf("Return status is %d \n", return_status);
return 0;
}
int Greeting(void)
{
char status;
printf("Welcome to the program. Would you like to continue?(Y/N)\n");
scanf(" %c", &status);
if (status == 'Y' || 'y') // Problem is probably here
{
printf("You have said %c.\n", status);
return 0;
}
else
{
return 1;
}
}
The first comparison you wrote here is correct, but the expression you wrote to the right of the statement is not a comparison. You directly write the expression 'y' there, since it does not correspond to 0 in the ASCII table, it is considered true and always gives the true result when combined with the OR expression.
if(status == 'Y' || 'y')
You should change like this;
if((status == 'Y') || (status== 'y'))
if((status == 'Y') || (status == 'y')) //Problem is probably here
{
printf("You have said %c.\n", status);
return 0;
}
You can check char like that
Yes, the problem is the "if" statement. You have to write:
if (status == 'Y' || status == 'y')
Variable return_status should be declared into main() function.
Related
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.
The problems seem to be on
Line 18: warning: comparison between pointer and integer
Line 22: error: expected expression before 'else'
What am I doing wrong? Is there a better way of doing this?
#include <stdio.h>
int main(void)
{
char pname[25];
char Y[1];
char N[1];
char choice[1];
printf("when responding to Yes or No questions use Y/N.\n");
printf("Hello,traveler Welcome to the Castle of Atal...."
"What is your name?\n");
scanf("%s", &pname);
printf("Greeting's %s What bring's you to the kingdom of Tharnos?\n",
pname);
printf("I see how intresting do you wish to enter %s ?\n", pname);
scanf("%c", &choice);
if (choice == 'Y');
printf("Enter %s...\n", pname);
else (choice == 'N');
printf("Farewell lost soul!\n");
return 0;
}
In your code, change the definitions
char Y [1];
char N [1];
char choice[1];
to
char Y;
char N;
char choice;
Otherwise, with the current definition, choice represents an array (of 1 element), which
is not required here, a single char will work just fine.
will trigger the warning for doing choice == 'Y', because, you cannot compare array with == operator.
That said,
scanf ("%c",&choice); should be scanf (" %c",&choice); to avoid the previous newline.
scanf ("%s",&pname); should be scanf ("%24s",pname); to avoid buffer overrun.
and , as mentioned in the answer by Mr. #iharob,
if (choice == 'Y');should be if (choice == 'Y') (the ; removed), otherwise, the if statement is effectively useless.
There is no conditional expression evaluation for else. You can make use of else if(choice == 'N'), though.
Your if statement do have issues
You should not put a semicolon at the end of an if statement, that would mean an if statement with an empty code block.
The syntax
else (choice == 'N');
is wrong, there is an equivalent though
else if (choice == 'N');
/* ^ you should add `if' after `else' */
Your code has more problems, but you didn't ask about them. #SouravGhosh did address them anyway.
Remove the semi-colons.
if (choice == 'Y'); <----- remove this semicolon
{
printf ("Enter %s...\n",pname);
}
The above is equivalent to:
if( choice == 'Y')
; /* Do nothing */
printf( ... );
else /* syntax error, not paired with an if statement */
;
Your syntax in not correct, you should use the right syntax:
if (condition) {
} else if (condition) {
}
or you can use this if you have something default to do when none of your conditions are true:
if (condition) {
} else if (condition) {
} else {
// you will get in this if when all of your conditions become false
}
I want this code to:
IF unsaved packets is greater or = 1,
then
print "There are unsaved packets"
"Would you like to saved them?"
"Type Y for Yes or N for No"
Get user input
IF User input = Y then function save
ELSE IF User input = N then exit
ELSE Return to menue
here is my current code, the problem is it won't take the input at all and if it does it doesn't use it to determine what happens after.
if(unsavedPackets >= 1)
{
puts("There are currently unsaved packets in the memory");
puts("\nWould you like to save them?");
puts("\nType Y for Yes or N for No");
getch(saveChoice);
printf("%c", saveChoice);
if(saveChoice == "Y")
{
puts("Saving records");
save(recordCount, records);
exit(1);
}
else if(saveChoice == "N")
{
exit(1);
}
else
{
printf("Returning to main menu");
}
}
break;
One problem is that
saveChoice == "Y"
where you should write
saveChoice == 'Y'
Similarly for "N"
In the first case, you are comparing char with const char * where second is pointer, not a character.
Your break statement will always be executed no matter if condition is true or false.
You are doing
if(savechoice =="Y")
it should be
if(savechoice == 'Y')
and likewise for 'N', since you are using char variable for storing user inputs.
There is problem with your if statement and also else if statement.
if(saveChoice == "Y")
and
else if(saveChoice == "N")
You are comparing a char with a string. You have to compare with char with a char like this
if(saveChoice == 'Y') and else if(saveChoice == 'N')
Always remember single quote for single character!!!
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This simple program asks the use's age and based on that displays a message.At the end if it,the user is asked if he would like to repeat the whole thing again.But I am getting the error
Break statement not within loop or switch
when I compile it. What does that mean and how do I correct it?
#include <stdio.h>
#include <string.h>
static int prompt_continue (const char *prompt)
{
printf("%s", prompt);
char answer[5];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n')
;
return 1;
}
return 0;
}
int main(void)
{
/*Creates a simple program using if else example. */
int age;
while (printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
scanf (" %d", &age); /*Enters age.*/
if (age < 18){
printf("You are young!\n");
}
else if (age > 18){
printf("Ah you're old!\n");
}
{
printf(" Woot.\n");
if (prompt_continue("Do you want to try again? Y/N") == 0)
break;
}
return 0;
}
Just trying to work through this, need a little help. Did I use the while loop wrong? Any thoughts would be helpful. Thanks!
You need to define the scope of your loop. In this code:
while (printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
...
if (prompt_continue("Do you want to try again? Y/N") == 0)
break;
what you actually need is:
while (true)
{
printf("Welcome, this program is designed for if else statements.\n"));
printf("Please enter your age.\n");
...
if (prompt_continue("Do you want to try again? Y/N") != 1)
break;
}
break stops the execution of while loop here.
The problem is that your break statement does nothing because it is not in a loop or switch, why did you put it there.
It's just what your error say!!break statement has to be within the body of a loop , if or switch-case and takes the control out of that block.This is what you should use here instead of break if you want to end the program at that point:
exit(0); //0 means successful termination, non-zero value means otherwise.
I am afraid your program needs an overhaul if you want the whole thing to repeat again.The logic is faulty.Let me check...
Edit Well,here's your full working program.I am sure you will understand the changes made.Else tell your confusions (if any) in a comment.Here's a brief explanation of the changes:
Th return statements in your prompt_contineu() function needed a little change,the getchar() there was not needed at all, there was no condition in the while loop in the main() function and its body was not well defined within {}, and last but not the least, the prompt_continue() function needed to be invoked within the while loop to get the job done.I hope you can see what the continue statement does. By the way this evil program said I am FRIGGIN OLD :-)
#include <stdio.h>
#include <string.h>
static int prompt_continue (const char *prompt)
{
printf("%s", prompt);
char answer[5];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
return 2;
if (answer[0] == 'n' || answer[0] == 'N')
return 3;
}
return 0;
}
int main(void)
{
/*Creates a simple program using if else example. */
int age;
while (1)
{
printf("Welcome, this program is designed for if else statements.\n");
printf("Please enter your age.\n");
scanf (" %d", &age); /*Enters age.*/
if (age < 18)
printf("You are young!\n");
else if (age > 18)
printf("Ah you're old!\n");
printf(" Woot.\n");
if(prompt_continue("Do you want to try again? Y/N")==3)
break;
else
continue;
}
return 0;
}