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
}
Related
I am making a program that reads input from a user then check the validity,
but for the while statement in the validateInput function I am getting an warning
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int ValidateUser(char *);
int ValidateInput(int);
FILE *database;
struct{
int year;
int unit;
float gpa;
char semester;
char grade;
char name[40];
}student;
int ValidateInput(int x)
{
while (x != 1 || x != 2 || x != 3) // code that causing a warning
return x;
}
int ValidateUser(char *input)
{
int result;
result = strcmp(input, student.name);
if (result == 0)
{
return 1;
}
else
{
while (result != 0)
{
printf("The Username you entered does not exit. Please enter correct name.");
}
}
return 1;
}
int main()
{
printf("\t----------------------------------------------------------\n");
printf("\t|\t\t\t\t Santa Monica College\t\t\t\t\t |\n");
printf("\t----------------------------------------------------------\n\n");
printf("\t\tWelcome to Santa Monica Student Record System.\n\n");
printf("Please Enter Your Option\n");
printf("\t1.View GPA/GRADE\n");
printf("\t2.Add New GPA\n");
printf("\t3.Modify Information\n");
int choice;
scanf("%d", &choice);
char UserName[40];
if(choice == 1)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
printf("The GPA of %s is %f , %c ", student.name, student.gpa, student.grade);
}
else if (choice == 2)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
}
else if (choice == 3)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
}
else
{
ValidateInput(choice);
}
return 0;
}
The ide was suggesting to add parentheses around x-values in the argument of while statement in the ValidateUser to make it silence
I've done some research on this warning and I found that the condition I made is not true so that's why I am getting it, but I am not quite sure what the problem is.
Can someone help me out with this???
In validateUser(), your program will reach the
while (result != 0)
only in the event that the while condition is initially true, so if it reaches the loop, it will enter it. The body of the loop does not modify result, so if it enters the loop, it will loop indefinitely.
Ultimately, if the first branch of the if / else is taken, then the function returns from within that branch, and if the second branch is taken then control never exits that branch. Either way, the
return 1;
at the end of that function cannot be reached. Of course, that's just a symptom. The infinite loop is the main problem.
It's unclear what behavior you actually want here, but what would be most in keeping with the name of the function would be for it to only evaluate whether the specified user name is valid, returning a result that conveys either "yes" or "no". There is no particular reason why such a function would need to loop at all.
You put while (result != 0) inside function ValidateUser(char *input) and never put a way to get out of the loop, resulting in the return value below it never running.
To fix this, you would need to add a break; somewhere in the loop to indicate that you are ready to leave the current loop, or make result = 0;
The difference between the two is that break; will indicate that the rest of the loop doesn't need to run and will jump out of the loop, or use result=0; to run the rest of the code in the loop and then jump out of it
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.
Basically I want to check if char a is not 'y' or 'n'. Been trying to figure it out for an hour now and could not find anything.
#include<stdio.h>
int yesno(char a){
do{
printf(":");
scanf("%s",&a);
if((a!='y')||(a!='n')){
printf("Incorrect awnser, try again\n");
}
}while((a!='y')||(a!='n'));
}
int main(){
printf("************************************\n");
printf("*Welcome to 'noname' 0.01 *\n");
printf("*Do you want to start y/n? *\n");
printf("************************************\n");
yesno(1);
return 0;
}
Could someone tell me how to do that? How to make it check if something is NOT something.
This code is what my understanding of C allows me to create, but it's not working correctly, it just loops:
Incorrect answer, try again
"if((a!='y')||(a!='n')){
printf("Incorrect awnser, try again\n");
}"
You could use a switch-case statement, with the default being the printf() statement.
switch(a) {
case 'y':
// do nothing
break;
case 'n':
// do nothing
break;
default:
printf("Incorrect answer, try again\n");
};
As suggested in the comments, you should use the && operator instead of || to check if a is neither 'y' nor 'n' like
if((a!='y') && (a!='n')){
printf("Incorrect awnser, try again\n");
}
}while((a!='y') && (a!='n'));
The condition ((a!='y') || (a!='n')) will always be true as a cannot be 'y' and 'n' at the same time.
And in yesno(), a is a char and not a char array capable of holding strings.
So
scanf("%s",&a);
should be
scanf("%c",&a);
as the format specifier for a char is %c whereas %s is for strings.
Even if a were a char array to store a string, the scanf() should've been
scanf("%s",a);
as array name in C decay into pointer to its base element.
And you could do away with that argument of yesno() as the initial value of a is irrelevant since a new value of a is read in at the beginning of yesno() and any changes made to a will not have any repercussion back in main() as the parameter is passed by value and yesno() doesn't return a value.
So, instead of making a a parameter, you could make it a local variable of yesno() like
void yesno(){//or yesno(void)
char a;
do
{
printf(":");
scanf("%c",a);
if((a!='y') && (a!='n')){
printf("Incorrect awnser, try again\n");
}
}while((a!='y') && (a!='n'));
}
And call it like
yesno();
in main().
You can use continue and break statements inside the if condition.
#include <stdio.h>
int yesno(char a){
do{
printf(":");
scanf("%s",&a);
if((a=='y')||(a=='n')){
break;
}
else{
printf("Incorrect answer, try again\n");
continue;
}
}while((a!='y')||(a!='n'));
}
int main(){
printf("************************************\n");
printf("*Welcome to 'noname' 0.01 *\n");
printf("*Do you want to start y/n? *\n");
printf("************************************\n");
yesno(1);
return 0;
}
I just changed the if condition and added the else part.
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));
}
This is the first question I've posted about C programming on here as I just started learning C just a few weeks ago. Ill write up my code and ask what my problem is :) If Anyone please knows how I can fix my mistake or whatever I should replace for my code please reply:)!
The problem I am having, is that if you run the code for yourself, you will see that everything works fine, except for the 'else' part in the statement. The issue I am having is that when someone types more than one letter, it will run the last printf statement more than once, and will printf as many times as the user inputs a character other than y or n.
The first part with the Y or N is working fine, yet if they type any number of other chars, it doesnt just state "Please select again", one time and then re-scanf, it types out at least 2 printfs, just for even one character entered, "Please select again" "Please select again", and then, if you type more chars for the answer, it will just type even more "please select again"'s.
Please help me understand what I am doing wrong as I'm so keen on learning to program properly, but I am just stuck here atm :)
#include <stdio.h>
#include <conio.h>
int main()
{
char answer;
int loop = 0;
printf("Please select. [Y/N]:\n");
while (loop == 0)
{
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
{
printf("Seeyou Later Aligator.\n");
break;
return 0;
}
else if (answer == 'n' || answer == 'N')
{
printf("Mmkay.\n");
break;
return 0;
}
else
{
printf("Please select again [Y/N]:\n");
loop = 0;
}
}
getch();
return 0;
}
scanf reads the required number of characters each time. If there are more characters, they are not ignored. They are read next time you call scanf. Hence you see multiple prints for every character. Inorder to explicitly ignore pending input, call fflush(stdin) after scanf. Which means to flush out any data in standard input stream.
Update:
fflush should not be used on input streams as said in comments. Use the accepted solution for ignoring output. However I recommend using toupper or tolower instead of bit hack.
The reason as many have pointed out is that your scanf is reading the extra newline character left in the input buffer after the user presses ENTER. So here is an alternative way to read input to avoid that whole mess:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char answer;
printf("Please select. [Y/N]:\n");
while (1)
{
scanf("%1s%*[^\n]", &answer);
answer |= 0x20;
if (answer == 'y')
{
puts("Seeyou Later Aligator.");
break;
}
else if (answer == 'n')
{
puts("Mmkay.");
break;
}
else
{
puts("Please select again [Y/N]:");
}
}
getchar();
return 0;
}
This will read just the first character found on stdin and ignore everything else after that and at the same time clear the input buffer of the newline character
break; is enough ... return will never be executed as you will break out of the while
Its printing more than once because scanf is taking in '\n' and extra inputs from previous entry
also the variable loop is pointless in your code
here is the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char answer;
int loop = 0;
printf("Please select. [Y/N]:\n");
while (1)
{
scanf("%c", &answer);
if (answer == 'y' || answer == 'Y')
{
printf("Seeyou Later Aligator.\n");
break;
//return 0;
}
else if (answer == 'n' || answer == 'N')
{
printf("Mmkay.\n");
break;
// return 0;
}
else
{
printf("Please select again [Y/N]:\n");
while(getchar()!='\n'){
getchar();
if(getchar() == '\n'){
break;
}
}
}
}
getchar();
return 0;
}
Output:
$ ./test
Please select. [Y/N]:
dddd
Please select again [Y/N]:
ffffff
Please select again [Y/N]:
y
Seeyou Later Aligator.