Why this switch case goes to the default case? - c

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");
}
}

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 )

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 :-)

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.

Thanks Everyone. I appreciate the help!
I should have noticed the data type though.
include
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");
}
}

Related

Basic C - Switch cases duplication

I am working on a project, where you answer a char, and if it is not one of the 4 answers, it tells you to try again. If it is not the correct one of the 4, it stops running. Here is a snippit.
#include <stdio.h>
#include <stdbool.h>
bool switchCheck = true;
char answer;
printf("A. English\nB. French\nC. Spanish\nD. German\n");
do{
scanf("%c\n", &answer);
switch (answer){
case 'C':
printf("Very nice ");
break;
case 'B':
case 'A':
case 'D':
printf("Sorry! Incorrect. Code Ends\n");
switchCheck =false;
break;
default:
printf("Try Again\n");
}
}while(switchCheck==true);
For some reason, when I input A, B, or D, it first prints the result for default, and if I do it again immediately afterward, it gives me the right input. Any help?
Thanks!
You are using scanf like
scanf("%c\n", &answer);
Instead use
scanf( " %c", &answer );
See the blank before the conversion specifier %c. It allows to skip white spaces.

Multi-character warning while get a char from keyboard in c

According to the operation entered from the keyboard, I want to do 5 operations with the switch structure, but gives an error. I tried also getchar & putchar functions...
int main()
{
char proc;
int firstNum,secondNum,result;
printf("* Multiplication\n/ Division\n+ Add \n- Minus\n%c Mode", '%');
printf("\nEnter the first number: ");
scanf("%d",&firstNum);
printf("\nEnter the second number: ");
scanf("%d",&secondNum);
printf("\nEnter the process: ");
scanf("%c",&proc);
switch(proc) {
case '*':
result=firstNum*secondNum;
printf ('%d',result);
break;
case '/':
result=firstNum/secondNum;
printf ('%d',result);
break;
case '+':
result=firstNum+secondNum;
printf ('%d',result);
break;
case '-':
result=firstNum-secondNum;
printf ('%d',result);
break;
case '%':
result=firstNum%secondNum;
printf ('%d',result);
break;
default:
printf('Warning!');
break;
}
warning: multi-character character constant [-Wmultichar]
warning: passing argument 1 of ‘printf’ makes pointer from integer
without a cast [-Wint-conversion]
For starters use
scanf(" %c",&proc);
^^^
(see the blank before the character &) instead of
scanf("%c",&proc);
And use double quotes to specify string literals in statements like this
printf ( "%d",result);
^^^^
or this
printf("Warning!");
^^^ ^^^
And you forgot one closing brace in the end of the program.

Switch statement inside a do-while loop in C [duplicate]

This question already has answers here:
abnormal behavior of scanf [duplicate]
(3 answers)
Closed 3 years ago.
I´m trying to make a program that tells you if a letter is a vowel o consonant and then ask the user if he/she wants to use the program again.
Using just the switch statement works totally fine. My problem comes when inserting the do-while loop. On the first try, the program works smoothly, but in the second and following loops, after asking the user if he wants to try again by typing 1, the program "jumps" the part where the user writes its input (scanf("%c", &letter)) and executes the rest of the program considering the previously typed 1 as the input and messing up everything.
I´ve tried looking for the answer on similar questions and videos, but I´m quite new and I just can´t grasp it. I have another program with a similar problem. I will really appreciate your help :)
int main()
{
char letter;
int new_try;
do {
printf("Is you letter a vocal or a consonant?\n");
printf ("\nPlease submit a letter:\n");
scanf("%c", &letter);
switch(letter) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("This letter is a vowel\n");
break;
default : printf("This letter is a consonant\n");
break;
}
printf("Do you wish to try again?\n [1.Yes 2. No]\n");
scanf("%d", &new_try);
}
while(new_try != 2);
return 0;
}
You need to clean the input buffer. Otherwise, as long as there are characters in your input buffer, the program will not wait for new input from user. Here is the solution.
#include <stdio.h>
int main() {
char letter;
int new_try;
do{
printf("Is you letter a vocal or a consonant?\n");
printf ("\nPlease submit a letter:\n");
scanf("%c", &letter);
while ((getchar()) != '\n');
switch(letter) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U': printf("This letter is a vowel\n");
break;
default : printf("This letter is a consonant\n");
break;
}
printf("Do you wish to try again?\n [1.Yes 2. No]\n");
scanf("%d", &new_try);
}while(new_try != 2);
return 0;
}
Update
As #David C. Rankin mentioned, using scanf(" %c", &letter); can also addresss your issue. However, it doesn't address a matching failure. In the above case, you also need to validate the input.

Code fails at case '0' - I don't understand why

Here is a minimal form of the code emphasizing the issue I have.
Code fails at "exit"(case '0') - program simply crashes. I suspect it is related to the while loop.
The issue occurs no matter what character i choose for the exit case (instead of '0').
#include <stdio.h>
void main()
{
int run=1;
char menu_option;
while (run==1)
{
printf("Choose case:\n");
scanf ("%s", &menu_option);
switch (menu_option) {
case '1':
printf("1");
break;
case '2':
printf("2");
break;
case '0':
run=0;
break;
default:
printf("Wrong input, try again\n");
}
}
}
menu_option is not a string, so %s is the wrong format specifier. You need %c, prefixed with a space to prevent whitespace (including newline) being interpreted as valid character input.
scanf (" %c", &menu_option);

Counting number of vowels and consonants in a string

I keep on getting a [Linker error]C:\Users etc and collect2: Id returned 1 exit status code errors on my program but I don't see anything wrong with it. This is my program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main (){
int vowels = 0, cnsnts = 0;
int i, length;
char string[100];
printf("Enter sentence:");
gets(string);
length = strlen(string);
for(i = 0; i < length; i++){
switch(toUpper(string[i])){
case 'A':
vowels++;
break;
case 'E':
vowels++;
break;
case 'I':
vowels++;
break;
case 'O':
vowels++;
break;
case 'U':
vowels++;
break;
default:
cnsnts++;
}
}
printf("The number of vowels are %d.\n", vowels);
printf("The number of consonants are %d.\n", cnsnts);
system("pause");
return 0;
}
Change
toUpper(string[i])
to
toupper(string[i])
add <ctype.h> header and turn on your compiler warnings.
First add
#include <ctype.h>
then change the camel case toUpper like so
toupper(string[i])
You must #include <ctype.h> and have mistakenly capitalized the u in upper. Your switch could also stand to be brought down a bit
switch(toupper(string[i])) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
break;
default:
cnsnts++;
}
This style takes advantage of fall-throughs. If a case doesn't end with a break (or return, continue, or goto) it will enter the case below it. This continues until a control flow altering keyword is hit. The switch above is functionally equivalent to your original, but a lot shorter.
You might also consider checking that string[i] is a letter at all with isalpha before the switch
if (!isalpha(string[i])) continue;

Resources