switch statement in C - c

Is the following switch statement correct? I mean can i use constant and character literal in one switch case statement?
It works in code but I am asking from good practices standpoint.
switch(arg[1]) {
case '4':
printf("value is 4\n");
break;
case '6':
printf("value is 6\n");
break;
case 'M':
printf("value is M\n");
break;
default:
break;
}

It works in code but I am asking from good practices standpoint.
Yes, it's fine to use char variables and constants in switch statements. It's very common to see that, for example, to process command line arguments. char is an integer type, and switch works as well with char as with any other integer type.

Related

How to use switch statement to assign a string value to a variable

The purpose of my program is to calculate the expenses for a trip between various cities. The program will give a list of source cities, followed by a list of destination cities. The user will be allowed to choose their cities by inputting the first letter of each city.
I want the program to be able to take the input from the user and assign it to one of the given cities.
//Declarations
char src_city[15];
char dest_city[15];
system("cls");
puts("\n");
printf("ENTER THE SOURCE CITY: \n\n");
printf("B for Baltimore\n\n");
printf("C for Chattanooga\n\n");
printf("N for Nashville\n\n");
printf("P for Pasadena\n\n");
puts("");
scanf("%c", &src_city);
switch(src_city)
{
case 'B': case 'b': ("Baltimore");
break;
case 'C': case 'c': ("Chattanooga");
break;
case 'N': case 'n': ("Nashville");
break;
case 'P': case 'p': ("Pasadena");
break;
}
getchar();
The 'B', 'C', 'N', and 'P' are the letters I want the user to input, and when they do to assign it to the corresponding city.
However, when I use this method I get the error:
"assignment to expression with array type".
I looked up this error and I was then told to use if/else if statements which in turn failed similarly. The switch statement method makes the most sense to me.
I need to assign the string value to the corresponding variable (src_city/dest_city) because I will need to call those variables later in a printf() statement.
You did not show the actual code which has problem, but guessing from the problem description ("assignment to expression with array type"), you are trying something like
src_city = "Baltimore";
which is invalid, as a variable of type array is not a modifiable lvalue and hence cannot be assigned to. You need to use strcpy(), like
strcpy(src_city , "Baltimore");

Why does scanf function get automatically previous '\n' value and how can I escape from this event?

I'm not new at writing code. But I'm just learning C language. I cannot understand this subject. Perhaps it is not an issue but now it is an issue for me. Would you please explain that?
Here is code, where I encounter with this:
#include <stdio.h>
int main(int argc, char *argv[])
{
char letter;
while (1)
{
printf("Enter a letter:\n");
scanf("%c", &letter);
switch (letter)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'u':
case 'U':
case 'o':
case 'O':
printf("%c is a vowel letter.\n", letter);
break;
case 'y':
case 'Y':
printf("%c is sometimes a vowel letter.\n", letter);
break;
default:
printf("%c is not a vowel letter.\n", letter);
}
}
return 0;
}
Output:
Enter a letter:
a
a is a vowel letter.
Enter a letter:
is not a vowel letter.
Enter a letter:
Change the format from "%c" to " %c" to make scanf discard all whitespace (as determined by isspace(), " \v\f\r\n\t" in the POSIX and C locales) before assigning the next character, whatever it may be.
Maybe a better alternative, read a whole line with fgets and then use sscanf to parse it instead.
As an aside, take care that scanf can always fail. On success, it returns the number of assigned arguments.
Also, I strongly suggest you read the scanf-manpage I linked above (or even better, the C standard on scanf), because there are quite a lot of pitfalls you may not know yet.

Switch Statement Not Executing Cases (c)

I made a switch statement, however, it only works with constants already set. If I try to use it with user input, only one of the cases work, every other one doesn't. Now no matter what I enter, it always uses the default case. I tried adding another getchar() to clear the \n character from the buffer but this isn't making a difference. Ill post the entire switch statement here :
char option=' ';
option=getchar();
switch(option){
//Parallel resistance calculations
case 'p':
CLEAR
//PResistance();
printf("RESISTANCE");
getchar();
break;
//Ohm's Law calculations
case 'o':
CLEAR
printf("OHM");
//Ohm();
break;
//Exits program
case 'q':
printf("Good bye! Stay safe in the laboratory! :)\nPress any key to exit");
getchar();
exit(0);
break;
//Error checking
default :
printf("Invalid input, Try again");
break;
}
}
while (option!='q');
I commented out the functions so I could use the print statements to test if its working.
Whenever you input a character or string from stdin in C, always make sure there is no \n in the input buffer. To do this, always getchar() after taking integer or float inputs.
In your case, maybe you've inputted an integer before inputting the character. So try to write a getchar() before taking the character input.

how to stop this code from hanging at wrong inputs?

I am learning C from ' programming in C' by Stephen Kochan. I am working on exercise no 4 of chapter 6 , writing a code that acts as a simple accumulator calculator. code is following. it works fine as long as inputs are provided in the right manner order.
#include<stdio.h>
int main(void)
{
float num, accum = 0;
char operator;
while(1)
{
printf("Enter the number and the operator ");
scanf("%f %c",&num, &operator);
if (operator == 'E') break;
switch (operator){
case 'S':
accum = num;
printf("= %g\n",accum);
break;
case '+':
accum = accum + num;
printf("= %g\n",accum);
break;
case '-':
accum = accum - num;
printf("= %g\n",accum);
break;
case '*':
accum = accum * num;
printf("= %g\n",accum);
break;
case '/':
accum = accum / num;
printf("= %g\n",accum);
break;
}
}
printf("= %g\n",accum);
printf("End of Calculation\n");
return 0;
}
but it hangs on the wrong inputs. what can be done to check such behaviour?
The short version is "don't use scanf()."
The problem is that scanf() provides only a limited indication of error, and leaves the erroneous data unread tp be picked up by the next call; especially if you're not bothering to do error checking, it's just going to spin forever on the bad data.
Always check the return code, so you know if it worked or not.
If you're doing line oriented input, use fgets() or similar to read an entire line, and sscanf() to parse from the line.
Do something sensible if the input isn't what you expected, instead of just barreling on through. (Your existing code just assumes it's always valid.)
Dont use scanf. Thats the first sight suggestion for this program. Use something like getchar like shown here They are dealing with the same problem as yours.
Check that scanf() returns 2, indicating that it has populated both arguments
Provide a default case in the switch statement that reports an error.
For increased robustness, you might want to read the whole line using fgets() (don't use gets() because it is vulnerable to buffer overflow) and parse the result using sscanf(). This is only necessary if you want to provide recovery from bad inputs. Otherwise, just stick with scanf() and exit(1) (and an error message) if anything goes wrong.

A problem with (switch) in C

scanf("%ld",&l);
printf ("l=%ld",l);
switch (l)
{
case'1':
XOR(&matrix1[10],&matrix2[10],m);
break;
case'2':
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}
When the program reaches switch, no matter what I enter (whether it's wrong or right), the program keeps showing the massage (Wrong input), though I've entered a right number (1 or 2).
Change your case labels from
case'1':
...
case'2':
...
to
case 1:
...
case 2:
...
Explanation: your switch value is an integer, not a character, hence you need integer constants for your case labels, not character constants.
Your case should be case 1 and not case '1'.
'1' != 1
Note: '1' is nearly 60 or something like that, 'cause single quotes mean "using char" (or it's ASCII code). Try removing 'em from your switch cases:
scanf("%ld",&l); printf ("l=%ld",l); switch (l) { case 1: XOR(&matrix1[10],&matrix2[10],m); break; case 2: AND(&matrix1[10],&matrix2[10],m); break; default: printf("\n\t\tWrong input"); }
Or you can change your input from numeric to char:
scanf("%c", &l);
But you aren't reading a character but your cases are characters. Re-write as follows:
switch (l)
{
case 1:
XOR(&matrix1[10],&matrix2[10],m);
break;
case 2:
AND(&matrix1[10],&matrix2[10],m);
break;
default:
printf("\n\t\tWrong input");
}
'1' and 1 are not the same.
Because your switch is relying on an integer. Whereas you're taking in a string. You'll need to run l through atoi first.
'1' is a char, the ASCII representation of the digit 1. Use plain 1 instead.
case 1:
/*...*/
break;
That's because:
case '1':
is not the same as:
case 1:
The second one is the one you seem to be expecting.

Resources