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.
Related
When the user inputs Yes,Only Maths,Only Science, the compiler executes Default.
I've tried with the same code but with Char replaced with Int it works as intended.. but with char it dosen't..
#include<stdio.h>
int main(){
char a;
printf("Have you passed in both maths and science?[Yes,Only Maths,Only Science]");
scanf(" %c", &a);
switch (a){
case 'Yes':
printf("That's amezing!");
break;
case 'Only Maths':
printf("That's good!");
break;
case 'Only Science':
printf("That's good!");
break;
case 'none':
printf("oof work harder next time!, i hope you will rock on that exam!");
break;
default:
printf("bozo do the typing right!");
break;
}
return 0;
}
A char by itself cannot store a string like "Yes". It will only store the first 'Y' and leave the rest. This is why none of the switch cases will match. Consider using string or char array to store an array of chars which can be compared. However, then the problem becomes that you cannot use switch with strings in C so you must use if, else.
#include <stdio.h>
int main(){
char a[15]; //15 should be a reasonable size
printf("Have you passed in both maths and science?[Yes,Only Maths,Only Science]");
fgets(a, 15, stdin);
if (strcmp(a, "Yes") == 0) printf("That's amezing!");
else if (strcmp(a, "Only Maths") == 0) printf("That's good!");
else if (strcmp(a, "Only Science") == 0) printf("That's good!");
else if (strcmp(a, "none") == 0) printf("oof work harder next time!, i hope you will rock on that exam!");
else printf("bozo do the typing right!");
return 0;
}
It is also recommended to use fgets instead of scanf to read strings.
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
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
}
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.
New programmer here with only some minor Java experience trying my hand at writing something in C. I want to ask someone a Yes/No question, do something depending on their answer, then ask them to press Enter to continue. I'm having two problems:
1.) I can't get the program to accept 'y', 'Y', or "Yes" as answers. I can get it to accept one, but not all three. The "logical OR" operator || isn't working.
2.) I can't get it to stop at "Press Enter to Continue" without two "Flush" commands of:
while (getchar() != '\n');
The code I have and am trying to use is as follows:
int main (int argc, const char * argv[]) {
printf("Would you like to continue? Please press y or n.\n");
if(getchar() == 'y'){
printf("You pressed yes! Continuing...");
}
else{
printf("Pressed no instead of yes.");
}
//flush commands go here
printf("\nPress ENTER to continue...");
if(getchar()=='\n'){
printf("\nGood work!");
}else{
printf("Didn't hit ENTER...");
return 0;
}
Any help would be appreciated, thanks.
Assuming that you are working in *nix environment,
You can create a buffer to store the incoming characters one after the other.
You have two cases:
1. Single character input
2. 3 character String
For all other cases you can blindly say that the input is not OK!
For case 1, i should be 1 and the character should be 'y' or 'Y'
For case 2, i should be 3 and the string should be 'Yes'
Any other case is incorrect. Here is the code:
#include<stdio.h>
int main()
{
char ch[3];
char c;
int i=0;
while(((c=getchar())!='\n')){
ch[i]=c;
i++;
}
ch[i]='\0';
if (i==1)
if (ch[0]=='Y'||ch[0]=='y')
printf("OK");
else
printf("Not OK");
else if(i==3)
if (strcmp(ch,"Yes")==0)
printf("OK");
else
printf("Not OK");
else
printf("NOT OK");
return 0;
}
I would recommend using something like this.
First off you might like to save the result of the first getchar() to test each possible value
eg
int c=getchar();
if(c=='y' || c=='Y')
....
The reason the "enter" part skips for the second test is because when you type 'y' or 'n' you press enter after to send your input - the \n is still in the buffer and it pulled by the next call to getchar()