I've been trying to make this if work I've tried to put scanf in every way possible and that was not the problem because it picks it up the "+" is stored as I see it on the printf below.
Can anyone figure out why not?
Thanks
float number1;
float number2;
float total;
char operator[1];
printf("Welcome to the calculator\n");
while(3>2)
{
printf("Pick a number\n");
scanf("%f", &number1);
printf("Que quieres hacer?\n");
scanf(" %c", &operator);
printf("You wrote %s\n", operator);
if(operator =='+')
{
printf("This works!");
}
}
This code snippet
scanf(" %c", &operator);
printf("You wrote %s\n", operator);
if(operator =='+')
{
printf("This works!");
}
is incorrect independent on how the variable operator is declared.
If the variable operator is declared like
char operator;
then this statement
printf("You wrote %s\n", operator);
invokes undefined behavior.
In this case you need to write
printf("You wrote %c\n", operator);
If the variable operator is declared as a character array as for example
char operator[N];
where N is some value then at least this statement
if(operator =='+')
does not make a sense and the condition will always evaluate to false.
Pay attention to that instead of this condition in the while loop
while(3>2)
it would be much simpler and readable just to write
while ( 1 )
Related
I am trying build a simple calculator. But whenever I input both the numbers, it skips straight to the default case and doesn't take in the input of operator. Here is my code -:
#include <stdio.h>
int main()
{
float num1, num2, result;
char opr;
printf("Enter the first number : ");
scanf(" %f ", &num1);
printf("\nEnter the second number : ");
scanf(" %f ", &num2);
printf("\nEnter the operation to be performed (+, -, *, /) : ");
scanf(" %c ", &opr);
switch (opr)
{
case '+' :
result = num1 + num2;
break;
case '-' :
result = num1 - num2;
break;
case '*' :
result = num1 * num2;
break;
case '/' :
result = num1/num2;
break;
default :
printf("\nWrong input.");
break;
}
printf("\nThe result is : %f", result);
return 0;
}
I tried to take the operator input twice and even left a space before "%c" so that it doesn't take newline as input. It skips straight to "Wrong input." section. Any help would be great.
Thank You.
The solution (as provided by Some programmer dude in comments here) is:
don't have trailing (or for almost all formats, leading) spaces in a scanf
Your comments indicate that you aready tried and verified that solution,
but have trouble understanding why it helps.
For visualisation, I modified your code without applying the solution, but with adding some helpful output.
#include <stdio.h>
int main()
{
float num1, num2, result;
char opr;
printf("Enter the first number : ");
scanf(" %f ", &num1);
printf("Got %f.\n", num1);
printf("\nEnter the second number : ");
scanf(" %f ", &num2);
printf("Got %f.\n", num2);
printf("\nEnter the operation to be performed (+, -, *, /) : ");
scanf(" %c ", &opr);
printf("Got %c.\n", opr);
switch (opr)
{
case '+' :
result = num1 + num2;
break;
case '-' :
result = num1 - num2;
break;
case '*' :
result = num1 * num2;
break;
case '/' :
result = num1/num2;
break;
default :
printf("\nWrong input.");
break;
}
printf("\nThe result is : %f", result);
return 0;
}
Try that code with the following input:
1.1<return>
1.2<return>
+<return>
*<return>
And you get the output (with input inbetween):
Enter the first number : 1.1
1.2
Got 1.100000.
Enter the second number : +
Got 1.200000.
Enter the operation to be performed (+, -, *, /) : *
Got +.
The result is : 2.300000
This is because:
1.1 gets scanned into num1, but not before a white space and a non-whitespace is found in input. This only happens with the first <return> and the first part of the second number 1.2. So you have to already enter the second number to make the first scanning work, because of the trailing whitespace in its format string. You have to do that before the prompt for the second number, because the prompt only gets to output after the fist scanning is done.
1.2 gets scanned into num2, but with the same problem, this time satisfied by the second <return> and the operator +. So you have to enter the operator before being prompted to.
+ gets scanned into opr, again with the same problem. It is already need before being prompted for, in order to satisfy the second scanning. It is not yet scanned, it just stops the scanning for a non-whitespace.
Then the prompt for the operator is in output, but at that point it was already required in input, though not being scanned yet.
Then the operator gets scanned into opr, but only if it is again followed by whitespace (the third <return>) and some non-whitespace (the *).
You can see that your program otherwise does as you programmed, yielding 1.1+1.2 being 2.3.
I am having some issues with the scanf function.
I am trying to printf a scanf result, but it only returns 0.00000
Can someone help me? Here is my code done so far:
#include <stdio.h>
int main() {
float grade;
char choise;
do {
printf ("Type your grade: ");
scanf("%f", &grade);
printf("Want to continue? s/n: ");
scanf(" %c", &choise);
printf("%s \n", &choise);
printf("%f", &grade);
}while(choise != 'n');
}
printf("%f", &grade); is wrong
try
printf("%f", grade);
But there are many other issues. At the very least, you must check the values returned by scanf, and you should use int main(void) or int main(int argc, char **argv). eg:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
float grade;
char choise;
do {
printf("Type your grade: ");
fflush(stdout);
if( scanf("%f", &grade) != 1 ){
fprintf(stderr, "Invalid input\n");
exit(1);
}
printf("Want to continue? s/n: ");
fflush(stdout);
if( scanf(" %c", &choise) != 1 ){
fprintf(stderr, "Invalid input\n");
exit(1);
}
printf("%c\n", choise);
printf("%f\n", grade);
} while( choise != 'n' );
return 0;
}
If you don't check the value returned by scanf, you don't know if any data was written into the variable. Since neither choise nor grade is initialized, attempting to read those values if scanf did not assign to them is undefined behavior. The behavior is also undefined if the input stream contains a value that cannot be represented as a float (eg, if it is a value greater than FLT_MAX), but that's really just an argument for avoiding scanf rather than a suggestion to try to make scanf usable. You can try to use scanf to make a user friendly interface, but it's really not worth the effort. Much better to simply abort on bad input. (If you want a user friendly interface, I would recommend you are using the wrong language.) See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html for more details on why you really ought to just avoid scanf completely.
These calls of printf
printf("%s \n", &choise);
printf("%f", &grade);
are incorrect.
In the first call you are trying to output a single character as a string. In the second call you are trying to output a pointer of the type float * as an object of the type float.
Instead you have to write
printf("%c\n", choise);
printf("%f\n", grade);
The lines
printf("%s \n", &choise);
printf("%f", &grade);
are wrong.
They should be
printf("%c \n", choise);
printf("%f", grade);
The %s format specifier should only be used for strings (null-terminated sequences of characters), not individual characters. The expression &choice does not point to a string, as the character sequence is not null-terminated.
Also, the %c and %f format specifiers require values, not addresses, when using them with printf. Only when using them with scanf should you pass an address.
I tried to make a basic calculator but whenever I make my inputs it adds rather than listening to my operator input.
I know that my if and if else statements aren't working but I don't really understand why. When I compile there are no errors and every other way that I've tried has resulted in many errors.
Here's the code:
#include <stdio.h>
int main(void) {
double num1;
double num2;
double x;
double operator;
printf("First number:\n");
scanf("%lf\n", &num1);
printf("Second number:\n");
scanf("%lf\n", &num2);
printf("Select operator:\n Division\n Multiplication\n Subtraction\n Addition\n");
scanf("%lf\n", &operator);
if (operator == '/' ) {
x=num1/num2;
}
else if (operator == '*') {
x=num1*num2;
}
else if (operator == '-') {
x=num1 - num2;
}
else {
x=num1 + num2;
}
printf("Result: %lf\n", x);
return 0;
}
Cheers!
Firstly, I'd avoid calling your variable 'operator' (it's a keyword in C++).
This is your variable:
double operator;
And here you read it as a double precision floating point number:
scanf("%lf\n", &operator);
And now you hope to treat it as a char:
if(operator == '-')
To fix this, change the type of operator to char:
char operator;
and read it as a char:
scanf("%c\n", &operator);
the posted code always results in addition because none of the comparisons ( '/', '-', '*' ) will ever compare equal to a double
I created a program of using 'switch' statement to make a simple calculator. If I first take the integer output & then the operator output, the value of b is always shown '0'. (the code is given here) However, if I first take the operator output, the program works just fine. What may be the reason for this? Thanks.
int a;
int b;
char sign;
printf("Enter two required integers: ");
scanf("%d", &a);
scanf("%d", &b);
printf("Enter the operator(+ or - or * or /): ");
scanf(" %s", &sign);
switch(sign){
case '+': printf("The summation of %d and %d is %d", a,b, a+b);
break;
case '-': printf("The subtraction of %d and %d is %d", a,b, a-b);
break;
case '*': printf("The product of %d and %d is %d", a,b, a*b);
break;
case '/': printf("The division of %d and %d is %d", a,b, a/b);
break;
default: printf("Enter the right operator noob!");
}
return 0;
}
scanf(" %s", &sign);
this is not correct. sign is char so it can only store 1 character, but you are trying to read a string which would need more than 1 characters so that would override the memory.
Rather use
scanf(" %c", &sign);
This is a basic question. You should keep in mind that a char can contain a single character from the keyboard. On the other hand, when you do character variable input or output, you should use %c for this purpose. On the other hand, we know, a string is built with multiple character combination. String variable is declared with char
variable[size];
And for string input or output, you need to use %s. As you used no 'string' here, you need to replace %s with %c and that should solve your issue!
I can't see why does the While loop just speed away and skipping the scanf for the char?
It would not even ask for my input and just loop like there's no tomorrow.
#include <stdio.h>
int main()
{
int number;
int multiply, ans;
char choice;
printf("-------------------------------------");
printf("\n MULTIPLICATION TABLE ");
printf("\n-------------------------------------");
do
{
printf("\nEnter an integer number:");
scanf("%d", &number);
printf("\nMultiplication of %d is :-\n", number);
printf("\n");
for(multiply=1; multiply<11; multiply++){
ans = number * multiply;
printf(" %d", ans);
}
printf("\n");
printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
scanf("%c", &choice);
printf("\n");
}
while(choice='Y');
printf("Thank You");
return 0;
}
scanf() doesn't do what you think it does (newline characters, buffering, etc.). It's preferred to use fgetc():
choice = fgetc(stdin);
For the same reason, you need to get rid of the trailing newline that
scanf("%d", &number");
leaves in the standard input buffer. To fix this, insert
fgetc(stdin);
after that particular call to scanf().
Also, C is not Pascal. The equality comparison operator - and the condition - you're looking for is
while (choice == 'Y')
the single equation mark denotes an assignment.
I think you need to use == operator for the comparison in while condition check as:
while(choice=='Y');
Currently you are using = operator, which is assigning Y to choice variable.
It has been a long time since I programmed in that language, but at a glance, you have:
while(choice='Y');
instead of:
while(choice=='Y');
== compares, = sets equal to. So the while loop is actually not checking the condition you're trying to set.