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.
Related
Hi please take a look on this code:
while (cont == 1) {
...
scanf_s("%d", &input);
if (0 < input <= 5){
switch (input) {
case 1:
printf("1");
break;
case 2:
printf("2");
break;
case 3:
printf("3");
break;
case 4:
printf("4");
break;
case 5:
cont = 0;
break;
default:
printf("Wrong input !");
break;
}
}else{
printf("Error, Not a number !");
}
}
If I input something that is not a number, it results in an infinite loop. How do I restrict char inputs?
You can use this:
if(scanf_s("%d", &input) != 1) {
printf("Wrong input !");
break;
}
You should ALWAYS check the return value of scanf_s anyway.
After the scanf_s() fails, you need to read at least one character (the character that it failed on); usually, it makes most sense to discard the rest of the line that the user entered:
while (cont == 1) {
int rc;
...
if ((rc = scanf_s("%d", &input)) < 0)
{
printf("EOF detected\n");
break;
}
if (rc == 0)
{
int c;
while ((c = getchar()) != EOF && c != '\n')
;
printf("Error, Not a number!\n");
continue;
}
if (0 < input <= 5){
switch (input) {
case 1:
case 2:
case 3:
case 4:
printf("%d", input);
break;
case 5:
cont = 0;
break;
default:
printf("Wrong input (1-5 required)!\n");
break;
}
}
}
If EOF is detected in the 'gobble' loop, you could detect EOF there and repeat the print and break the loop immediately. OTOH, the next scanf_s() should also report EOF, so it isn't 100% necessary. It depends a little on where the prompting occurs; if you get EOF, you probably shouldn't prompt again, so maybe the test after the inner while loop should be:
if (c == EOF)
{
printf("EOF detected\n");
break;
}
else
{
printf("Error, not a number\n");
continue;
}
You can play with variants of the 'gobble' loop that read up to a newline or a digit, and use ungetch(c, stdin); to return the digit to the input stream for the next call to scanf_s() to process — you probably wouldn't prompt for more input if you're going to process the already entered digit (that would confuse).
There are endless other games you can play. One option to consider is limiting the number of failed inputs before you give up — if the user hasn't entered a valid number in 10 tries, they probably aren't going to.
Note how the error processing tells the user what the valid range of numbers is; that helps them get it right. Also notice that the messages have a newline at the end; that's generally a good idea. In contexts outside interactive I/O, the newline can help ensure that the output appears when it is printed, not some arbitrary time later when some other print adds a newline, or the output buffer fills up and the pending data is flushed after all.
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.
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 wrote a C program wherein I am accepting a numeric input from the user. However, if the user inputs a character, then I have to show that it is an invalid input and make the user enter a number again. How do I achieve this? I am writing the program using gcc compiler in Ubuntu. The search results on Google suggest to use isalpha function...however, it is not available in the libraries I guess.
I also tried the below...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void main()
{
system("clear");
if (isdigit(1))
printf("this is an alphabet\n");
else
printf("this is not an alphabet\n");
}
You will need to use scanf to get user input with %d as you want to scan an integer. In your case, scanf will return 1 on sucessfull scanning.
int num;
//loop to prompt use to enter valid input
while(scanf("%d",&num)==0) //scanning an integer failed
{
printf("invalid input ! Try again\n");
scanf("%*s"); //remove the invalid data from stdin
}
The functions isalpha() and isdigit() works when you are getting a character input using %c in the scanf. If you want to scan input using %c , then you can simply check like what you have done in your code provided that you get input using %c. Note that character 1 ('1') is note equal to integer 1 . Characters have their integer values as represented by the ASCII table. Your program to prompt the user again when the user enters anything other that a number using %c will look like this:
char ch;
while(1){
printf("Enter a number\n");
scanf(" %c",&ch);
printf(Your input is %c\n",ch);
if(isdigit(ch))
{
printf("This is a number\n");
break;
}
else
printf("This is not a number. Invalid input\n");
}
I tried the below code which worked fine..using isdigit()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void main()
{
system("clear");
char str[1];
printf("Enter a number\n");
scanf("%s",str);
printf("What you entered was %s\n",str);
if(isdigit(str[0]))
printf("this is not an alphabet\n");
else
printf("this is an alphabet\n");
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include<ctype.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
bool check=true;
while(check)
{
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
{
printf("%c is an alphabet.",c);
check=true;
break;
}
else
{
printf("%c is not an alphabet.",c);
check=false;
}
}
return 0;
}
You can write your own. It's better to check digits since there're less cases for digits.
bool isDigit(char c) {
bool rtn = false;
switch(c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
rtn = true;
break;
default:
rtn = false;
break;
}
return rtn;
}
I've been writing a little C code, and I want switch to compare multiple characters in a string, but currently I can only get it to check one character.
What i would really like is for it to test if the input was yes, rather than just the first character of the input, so in this case, the y, or the n.
Here is my code:
switch (d[0]){
case 'y':
printf("Welcome ");
printf("%s\n", c);
break;
case 'n':
printf("Please Select A New User Name\n");
memset(&c[0], 0, sizeof(c));
goto name;
break;
case 'N' :
printf("Please select a new user name\n");
memset(&c[0], 0, sizeof(c));
goto name;
break;
case '\n':
printf("that is not a valid command, please try again\n");
memset(&d[0], 0, sizeof(d));
goto LOOP;
break;
case 'Y':
printf("Welcome ");
printf("%s\n", c);
break;
default :
printf("That is not a valid command, please try again\n");
goto LOOP;
break;
That's not what switch is for, it's for taking decisions based on an integer-valued expressions.
You need to use strcmp() to compare strings:
if(strcmp(d, "y") == 0)
{
printf("Welcome");
/* ... */
}
else if(strcmp(d, "n") == 0 || strcmp(d, "N") == 0)
{
printf("Please select a new user name\n");
/* ... */
}
Note that the above assumes that d is a properly-terminated string, i.e. not just a char.
ISO 9899 6.8.4.2
The controlling expression of a switch statement shall have integer type.
So passing string is not possible.
You simply can't.
Instead you have to resort to multiple if and else if statements comparing either individual characters or using strcmp to compare strings.
May be you can do it this way?
switch (d[0])
{
case 0x79:
printf("Welcome ");
printf("%s\n", c);
break;
case 0x6E:
printf("Please Select A New User Name\n");
memset(&c[0], 0, sizeof(c));
goto name;
break;
case 0x4E:
printf("Please select a New user name\n");
memset(&c[0], 0, sizeof(c));
goto name;
break;
case 0x0A:
printf("that is not a valid command, please try again\n");
memset(&d[0], 0, sizeof(d));
goto LOOP;
break;
case 0x59:
printf("Welcome ");
printf("%s\n", c);
break;
default :
printf("That is not a valid command, please try again\n");
goto LOOP;
break; // Does it really need a break here?????
}