Switch function directly goes to default. What's the issue? - c

I am new to C and am writing a simple code of converting temperatures. The code is still incomplete but still should give me some output
#include<stdio.h>
void main()
{
float temp;
char choice;
printf("\n 1. Celcius to Farenhite\n 2. Farenhite to Celcius\n What do you want to convert from? : ");
scanf("%c", &choice);
switch (choice)
{
case 1:
printf("Enter temperature in Celcius: ", temp );
scanf("%f", &temp);
break;
case 2:
printf("Enter temperature in Farenhite: ", temp);
scanf("%f", &temp);
break;
default:
printf("Invalid Choice");
break;
}
}
When I run this it asks "what do you want to convert from?" and shows the options. But when I enter 1 or 2, it directly prints and shows "Invalid Choice".
Pls tell me what's wrong :(

1 is 'int' and not a char.
1 and '1' are different.
This is the edited code
#include<stdio.h>
void main()
{
float temp;
char choice;
printf("\n 1. Celcius to Farenhite\n 2. Farenhite to Celcius\n What do you want to convert from? : ");
scanf("%c", &choice);
switch (choice)
{
case '1':
printf("Enter temperature in Celcius: ", temp );
scanf("%f", &temp);
break;
case '2':
printf("Enter temperature in Farenhite: ", temp);
scanf("%f", &temp);
break;
default:
printf("Invalid Choice");
break;
}
}

The number one is not the same as the digit "1". You are entering the character "1" and your switch statement is checking for the number one.
The number one is how many hearts I have. It can be written with the digit '1' but any number of other ways.
The digit '1' is a character. It is sometimes use to represent the number one but can also be used for other things. A variable of type char can hold the digit 1 since digits are characters.
Your switch statement is checking for the number one. You want to check for the character 1.

'1' is a character, whereas 1 is an integer. Your switch statement can't find a case to match with, hence it goes to default.
Is that the complete code? You're not converting anything here, you're only asking the user for the temperature and storing it in a variable.
OT: Indent properly, your code is messy and difficult to read. And do not use scanf for taking input. You may want to check out this link http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html.

This is a common misunderstanding for novices and occasional typo for experienced programmers(*).
1 means "the integer value one" (it is the integer literal for the value of 1).
Assuming your on an ASCII compatible platform(**) that is the character with ASCII code 1 (the non-printing character called Start of Header - SOH).
The ASCII Code for the character 1 is actually 49. But you should write:
case '1':
Because those apostrophes identify the 1 as the character representing 1 not the numeric value of 1.
The compiler will interpret '1' as actually meaning character of 1 meaning the (codepoint) value of 49.
In C char has a deeply dual role as a numeric type and as the smallest unit of text and accidental mixing of those roles causes endless confusion.
Arguably char has 3 roles. The smallest arithmetic type, the smallest unit of text (a character) and the unit of addressable memory (byte).
There are historical reasons why those roles are conflated in C.
(*) But I can't find a good answer for it even though there should be thousands of times this has been asked.
(**) C does not specify a character set but if you working on a platform that isn't ASCII compatible you will know about it. Unless you've found something in your Grandparent's basement and they're sadly not around to explain it. This footnote exists for the likely comments to the effect that C doesn't specify a character set.

Your program reads a byte from stdin and compares that to the values 1 and 2. It is unlikely the user can type these byte values as they correspond to control characters CtrlA and CtrlB1. The byte values representing the digits 1 and 2 typed by the user are noted in C as '1' and '2'. These are called character constants and are int values for the encoding of the corresponding characters.
Furthermore, you should:
indent your code more consistently.
define main with a return type int
test the return value of scanf()
fix the spelling of Fahrenheit, named after German physicist Daniel Gabriel Fahrenheit and Celsius, named after Swedish astronomer Anders Celsius.
1: From a unix terminal, one can actually enter these byte values by hitting CtrlV CtrlA and CtrlV CtrlB, respectively, followed by Enter.
Here is a modified version:
#include <stdio.h>
int main() {
float temp;
char choice;
printf(" 1. Celsius to Fahrenheit\n"
" 2. Fahrenheit to Celsius\n"
" What do you want to convert from? ");
if (scanf(" %c", &choice) != 1)
return 1;
switch (choice) {
case '1':
printf("Enter temperature in Celsius: ", temp);
if (scanf("%f", &temp) != 1)
return 1;
printf("%g degrees Celsius is %g degrees Fahrenheit\n",
temp, 32 + temp * 9 / 5);
break;
case '2':
printf("Enter temperature in Fahrenheit: ", temp);
if (scanf("%f", &temp) != 1)
return 1;
printf("%g degrees Fahrenheit is %g degrees Celsius\n",
temp, (temp - 32) * 5 / 9);
break;
default:
printf("Invalid choice\n");
break;
}
return 0;
}

Related

Problem in code of C language In applying Arithmetic Operation between Inputs? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
Improve this question
/I took input from user as 'a' and 'b' but in 'b' it takes 0 by default ..... whatever i give in 'b' as input it showing 0 as 'b' on applying Operation....
C code ....../
#include <stdio.h>
int main()
{
int a,b;
printf("Enter the I no. : ");
scanf("%d",&a);
printf("Enter the II no. : ");
scanf("%d",&b);
char c;
printf("Enter the Operation : ");
scanf("%s",&c);
switch (c)
{
case '+':
printf("Addtion of %d and %d = %d",a,b,a+b);
break;
case '-':
printf("Subtraction of %d and %d = %d",a,b,a-b);
break;
case '*':
printf("Multiplication of %d and %d = %d",a,b,a*b);
break;
case '/':
printf("Division of %d and %d = %d",a,b,a/b);
break;
}
}
You declared an object of the type char
char c;
So to input a value for the object you need to use conversion specifier %c instead of %s
printf("Enter the Operation : ");
scanf(" %c",&c);
Pay attention to the leading space in the format string. It allows to skip white space characters.
Also before performing division you need to check whether b is not equal to 0.
And it is desirable to include the case label default in the switch statement for an invalid inputted operation.
Also some operations as for example the multiplication can result in overflow. To avoid overflow you should cast operands to the type long long int In this case the calls of printf will look the following way as for example
printf( "Addtion of %d and %d = %lld\n", a, b, ( long long int )a + b );
scanf("%d",&b); appears to be correct code to read a decimal numeral into b. If a non-zero number is entered but b later appears to be zero, a likely explanation is that the mistaken use of scanf("%s",&c); writes a null byte into b.
%s is for reading multiple characters into an array of char. In addition to reading characters from input, it writes a null byte into the array to mark the end of the characters. However, c is a single character, not an array. If you entered a character such as “+” (followed by pressing Enter) then scanf("%s",&c); will write the character into c and then write a null character to the next byte in memory.
If the compiler happened to put b just after c in memory, that will alter the value stored in b.
Do not use scanf("%s",&c); to read a single character. Use " %c". The space character tells scanf to skip white-space (such as the new-line character that will be in the input stream after the user enters a value for b and presses Enter) %c tells scanf to read a single character: scanf(" %c", &c);.

My program topped working when I enter a number

I used to compile in VSCode with mingw-64 in Windows 10.
Please rectify my errors.
[1]: https://i.stack.imgur.com/j5CKZ.jpg [
#include <stdio.h>
int main() {
float rupees,result;
int choice;
printf("Enter 1 for USD\n");
printf("Enter 2 for EUR\n");
printf("Enter 3 for AUS\n");
printf("Enter 4 for UAE Dirham\n");
printf("Enter amount in Rupees\n");
scanf("%d",&rupees);
printf("Enter your choice\n");
scanf("%d",choice);
switch (choice)
{
case 1:
result=rupees*73.04 ;
break;
printf("%f Amount equal to %f USD\n",rupees,result);
case 2:
result=rupees*88.82 ;
printf("%f Amount equal to %f EUR\n",rupees,result);
break;
case 3:
result=rupees*56.36 ;
printf("%f Amount equal to %f AUS\n",rupees,result);
break;
case 4:
result=rupees*19.89 ;
printf("%f Amount equal to %f Dirham\n",rupees,result);
break;
default:
printf("Enter correct choice");
break;
}
return 0;
}
Firstly, Let me try to review your thought process before getting onto the code.
You declared and read variables to store the value in rupees, the user choice and the conversion result.
You wrote a switch case to activate a particular block of code based on user choice and in a default case, you wrote a "printf" statement to convey to the user that the choice was invalid.
However, the program is tainted and below are the reasons why:
The Logic is invalid, as per your program, 1 rupee must be equivalent to 73.04 USD, 88.82 EUR,56.36 AUS and 19.89 Dirham accordingly which is a falsity. The vice versa is true! 1 USD=73.04 Rupees and so on. Quick Fix would be to replace "*" operator with "/" operator at every switch case.
You cannot actually read a fractional value for rupees using the above code as the placeholder for a float data-type in C is "%f" and not "%d".
In the line where you wanted to read the user choice, you did not use the Address-Of Operator(&) i.e you did not give the address location into which the value is to be read, you gave the identifier itself.
In the first switch case, you placed the break statement before the "printf" statement. Which would mean that you would break the control flow even before you would print something on your console.
In a default case, you asked the user to enter a valid choice but the problem is that the control terminates thereafter leaving no scope to re-enter the choice. A quick fix to this is to put the switch case within a loop or alternatively, just display an error message stating "Invalid Choice". (Note that such issues are called semantic errors where the structure of the program is valid as per the language rules but the overall logic and flow of the application is inconsistent).
Miscellaneously, there are some message-format errors that could be made better.
Ex: You don't have to ask to enter his/her choice given that you prior mentioned "Enter 1 for USD.....2 for EUR.....". Also, you could probably replace Amount with Rupees while printing the end-result to make the output more elegant and clear.
Last but not the least, the flow of your code is not so appropriate. Initially you display the entire catalogue to the user to choose from and then you ask the user to enter the value in rupees(you could ask the user to enter the rupee value irrespective of his conversion scale). By slightly rearranging the code, the usability of your script increases.
Want to look at Rectified Code? Here you go!
Rectified Code:
#include <stdio.h>
int main()
{
float rupees,result;
int choice;
printf("Enter amount in Rupees\n");
scanf("%f",&rupees);
printf("Enter 1 for USD\n");
printf("Enter 2 for EUR\n");
printf("Enter 3 for AUS\n");
printf("Enter 4 for UAE Dirham\n");
scanf("%d",&choice);
switch (choice)
{
case 1:
result=rupees/73.04 ;
printf("%f Rupees is equivalent to %f USD\n",rupees,result);
break;
case 2:
result=rupees/88.82 ;
printf("%f Rupees is equivalent to %f EUR\n",rupees,result);
break;
case 3:
result=rupees/56.36 ;
printf("%f Rupees is equivalent to %f AUS\n",rupees,result);
break;
case 4:
result=rupees/19.89 ;
printf("%f Rupees is equivalent to %f Dirham\n",rupees,result);
break;
default:
printf("That was an Invalid Choice!");
break;
}
return 0;
}

Is there a limit to how many times the scanf function can be used? [duplicate]

This question already has answers here:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
Closed 9 years ago.
In an effort to get back into the flow of C programming, I've been typing up some simple test programs. I've ran into a strange problem with the scanf function. I have 3 in the following code, but only the first 2 are initialized; the third scanf is ignored. Is this normal, or am I doing something wrong? I've been staring at this code for the last half an hour and I can't find any errors.
#include <stdio.h>
int math(int a, int b, char selection) {
int result;
switch (selection) {
case 'a':
result = a + b;
break;
case 's':
result = a - b;
break;
case 'm':
result = a * b;
break;
case 'd':
result = a / b;
break;
}
return result;
}
int main() {
int num1 = 0;
int num2 = 0;
int result = 0;
char selection;
printf("Enter first number: ");
scanf("%i", &num1);
printf("Enter second number: ");
scanf("%i", &num2);
printf("\n[a] Add\n[s] Subtract\n[m] Multiply\n[d] Divide\n\nWhich one: ");
scanf("%c", &selection);
result = math(num1, num2, selection);
printf("%i", result);
return 0;
}
To answer your over all question:
Is there a limit to how many times the scanf function can be used?
No, no there is not.
but that's not what is happening here anyway.
When you do something like this:
printf("Enter second number: ");
scanf("%i", &num2);
You're actually entering two values on stdin, first a number, second an invisible newline character.
you can't see that, but it's there
V
> Enter second number: 3\n
The way scanf() works, it will read and store input from stdin to your variables until they are all filled, then it will leave the rest. In my example 3 got stored to num2 and '\n' is left on stdin Then when this code runs:
scanf("%c", &selection);
It will look on stdin and find the newline character ('\n') sitting there. This can be stored to a character type, so it will fill selection with it.
One way to fix this is to change your code to:
scanf(" %c", &selection);
The space before the % tells scanf to ignore any white space (including newlines) that are at the start of the stdin buffer.
Side note on debugging:
When you think something is going wrong, either use a debugger or print some values to give you confidence and understanding. For example, I would update your code as such:
printf("\n[a] Add\n[s] Subtract\n[m] Multiply\n[d] Divide\n\nWhich one: ");
int ret = scanf("%c", &selection);
printf("Scanf I think failed. Return value is: %d. Selection is: %c (%d)\n",
ret, selection, selection);
You can find the meaning of return values from man pages. In this case the return code here will tell you how many items were successfully matched and assigned. You'd see 1 here, so you know the call worked. Your output would look like:
Scanf I think failed. Return value is: 1. Selection is:
(10)
This tells you that scanf did indeed get something, you don't see a character printed, but the output skipped a line (suspicious) and the ASCII value of what was printed was 1010, looking that up you'll see it's a newline character.

What is the best way to apply an arithmetic expression to 2 binary numbers provided by the user in C?

I am writing a program that accepts 2 binary numbers from the user. Then the user selects a arithmetic expression (+ - / * %) to apply to the numbers. I have the general input code but am at a loss as to where to go next. I'm fairly new to the C language. Here is what I have so far.
#include <stdio.h>
int main(){
int number1, number2;
char expression;
//Basic instructions at the beginning of the program
printf("This is a program to execute arithmetic in binary.\n");
printf("The program will ask you for input in the form of two binary numbers separated byan arithmetic expression (+ - / * %).\n");
printf("The binary numbers must be only 1's and 0's and a maximum of seven digits.\n");
printf("You may exit the program by typing 'exit'.\n");
//Obviously an incomplete do statement, need a loop
do {
//Getting input from the user
printf("\nEnter first binary number: ");
scanf("%d", &number1);
printf("Enter second number: ");
scanf("%d", &number2);
printf("Which expression would you like (+ - / * %): ");
scanf("%c", &expression);
}
}
Since expression is a char(and not char[]), you can use switch-case:
int result;
switch(expression){
case '+':
result=number1+number2;
break;
case '-':
result=number1-number2;
break;
case '*':
result=number1*number2;
break;
case '/':
result=number1/number2;
break;
}
You might also want to add a default, in case the user entered an invalid operator.

C calculator program keeps giving error when I input "sine"?

Hi I am new to programming and have been working on a calculator for a while now. I am trying to add some trig functions in and I am having trouble with sine. The other functions work (+, -, *, /) but when I put in "sine" it skips to the part of the code where it says it is an incorrect function. Please help out with my code. Thanks!
#include <stdio.h>
#include <math.h>
int main()
{
float firstnum, secondnum, angle, answer, pi;
char function, sine;
pi = atan(1.0)*4;
printf("\nHello and welcome to my calculator!\n");
while(1)
{
printf("\nPlease input the function you would like to use. These include +, -, *, /, sine.\n");
scanf("%s", &function);
switch(function)
{
case '+':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum+secondnum;
break;
case '-':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum-secondnum;
break;
case '*':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum*secondnum;
break;
case '/':
printf("\nNow please input the two variables.\n");
scanf("%f", &firstnum);
scanf("%f", &secondnum);
answer = firstnum/secondnum;
break;
case 'sine':
printf("\nPlease enter the angle.\n");
scanf("%f", &angle);
answer = sin(angle);
break;
default: printf("Sorry, that is an incorrect function. The only available choices are +, -, *, /, sine.");
break;
}
printf("Your answer is %f \n", answer);
printf("\nWhen you are ready to quit, simply press Ctrl + C or just hit the X button in the top right.\n");
}
return 0;
}
'sine'
That is a multi-character literal. function is a single character. It's integral value is checked in the switch statement. You will likely never be able to consume a single character from the user which matches sine in the way that you are attempting to do so. Read a string (a char*) instead.
From the standard:
C99 6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."
C does not have a first class string type. This means that you cannot use a switch statement for strings, you will need to use functions such as strlcmp for string comparison.
Depending on your objective (either making a calculator, or learning C) it might be wise to either switch to a different language with higher abstraction levels, or start with lower level exercises from a good C textbook.
Also, please be aware that working with strings and user input correctly in C, that is without security holes, is much more difficult than it would seem at first. If your objective is learning a language perhaps learning C++ is a better bet where you have std::string to handle your comparisons and iostreams to handle your input and output.

Resources