Reputation: 23
The code is supposed to check for a vowel input. If found, it would print "Vowel" and if there is none it should print "consonent". But the compiler is going to the default
case regardless of the input and I can't find where the mistake is. Please Help.
Here's my code:
#include<stdio.h>
void main()
{
char ch;
printf("Insert a Char \n");
scanf("%d", &ch);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel");
break;
default:
printf("Consonent");
}
}
Upvotes: 0
Views: 83
Reputation: 23
Thanks Everyone. I appreciate the help! I should have noticed the data type though.
void main() {
char ch;
printf("Insert a Char \n");
scanf("%c", &ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("Vowel");
break;
default:
printf("Consonant");
}
}
Upvotes: 0
Reputation: 310920
The conversion specifier %d
in this call
scanf("%d", &ch);
is invalid. It tries to read a number. So entering a letter like 'A' results in input error.
The compiler can issue a warning or even an error reporting that for example
format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘char *’
Because using an invalid format can result in undefined behavior.
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
char s[] = "ABCD";
puts( s );
scanf( "%d", ( int * )s );
puts( s );
return 0;
}
If for example even to enter a valid ASCII code as for example 65
of the letter 'A'
then the program output might look like
ABCD
A
That is the memory occupied by the array was overwritten.
Instead use the following call.(if you want to skip white spaces)
scanf( " %c", &ch );
or the following call
scanf( "%c", &ch );
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
Upvotes: 1
Reputation: 4677
you should use "%c" as the format. when you use "%d", the value is 0 (because no integers have been detected in the input string). Refer to https://en.cppreference.com/w/c/io/fscanf#Example.
This issue, and void main()
instead of int main()
, should produce a compiler warning.
Upvotes: 0
Reputation: 343
First thing %d accepts an integer, not a character so correct this and run then place break after each case ends if you don't place break it will run all case till the end which is the default. Example:-
char ch;
printf("Insert a Char \n");
scanf("%c", &ch);
switch(ch)
{
case 'a':printf("Vowel");
break;
case 'e':printf("Vowel");
break;
case 'i':printf("Vowel");
break;
case 'o':printf("Vowel");
break;
case 'u':
printf("Vowel");
break;
default:
printf("Consonent");
}
Hope it will help. Happy coding :-)
Upvotes: 0