how to choose an operator and show it - c

I don't know what is wrong wiht my program, i tried to enter the numbers from keyboard and enter any operator and sort them like "a+b", but I don't know if it is correct so far, I don't have errors, but when I enter an operator it shows "You did not enter an opperator" it goes straight to the else, I don't know why. If you could please help me, thank you!
int main()
{
int a, b;
int op;
int var = '+';
int var1= '-';
int var2= '/';
int var3= '*';
printf("Choose your 2 numbers: ");
scanf("%i", &a);
scanf("%i", &b);
printf("Choose your operator (+, -, *, /): ");
scanf("%i", &op);
if(op == var || op == var1 || op == var2 || op == var3)
{
printf("The correct order is: %i, %i, %i", a, op, b);
}
else
{
printf("You did not enter an operator");
}
return 0;
}

So, first of all it'd be better to declare your op variable as a char instead of int as you are trying to read a character from the keyboard and not an integer number. Indeed if your try to print out your op variable as it is in your code you'll find out that its value is 0.
After changing this you should also change all %i for that variable to %c. This though will give a problem when using scanf(), which is that it will look like it got skipped. This is because the scanf() will read the last \n from the user as the character and put it in your variable.
To fix this you just need to put a space before %c so that the scanf() will skip the first whitespace character and then read from the keyboard. You can find more detailed explanation about this here
Anyway down here there's the working code.
int main()
{
int a, b;
char op;
int var = '+';
int var1 = '-';
int var2 = '/';
int var3 = '*';
printf("Choose your 2 numbers: ");
scanf("%d", &a);
scanf("%d", &b);
printf("Choose your operator (+, -, *, /): ");
scanf(" %c", &op);
if(op == var || op == var1 || op == var2 || op == var3)
{
printf("The correct order is: %i, %c, %i", a, op, b);
}
else
{
printf("You did not enter an operator.");
}
return 0;
}

Related

passing argument 1 and 2 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]

Hello so I've been working a little prgramme which is sort of a calculator (I'm a beginner) and well as you can see in the tittle at then end of the code, the two if strcmp doesn't work. And vscode is telling me (for the strcmp) Exception has occurred. Segmentation fault. But gcc is telling me what is in the tittle.
#include <stdio.h>
#include <string.h>
int main()
{
float num1;
float num2;
float anwser;
int rnum = 1;
int hi = 0;
char operator;
char ifyorn;
char y = 'y';
char n = 'n';
while (hi == 0)
{
printf("Enter operator +, -, /, x: ");
scanf(" %c", &operator);
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
switch (operator)
{
case '+':
anwser = num1 + num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '-':
anwser = num1 - num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case 'x':
anwser = num1 * num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '/':
anwser = num1 / num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
default:
printf("This is not a valid character please try again :(");
break;
}
if(strcmp (ifyorn, n) == 0)
{
printf("%f", anwser);
hi == 1;
}
if(strcmp (ifyorn, y) == 0)
{
hi == 0;
}
}
}
The variables ifyorn, y and n are declared having the type char.
char ifyorn;
char y = 'y';
char n = 'n';
The function strcmp expects arguments of the pointer type char * that point to strings.
So these if statements
if(strcmp (ifyorn, n) == 0)
and
if(strcmp (ifyorn, y) == 0)
are incorrect. Instead you should write
if ( ifyorn == n )
and
if ( ifyorn == y )
Also instead of assignments you are using the comparison operator in these statements
hi == 1;
and
hi == 0;
You need to write
hi = 1;
and
hi = 0;
Increasing the variable rnum looks senseless
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
Why not just to write
printf("Enter num %d :", 1 );
scanf("%f", &num1);
printf("Enter num %d :", 2 );
scanf("%f", &num2);
And in the code snippet under the label default you should add one more statement
default:
printf("This is not a valid character please try again :(");
ifyorn = y;
break;
You don't have to be mean to the guy ,he is learning.
You are getting this error because you are passing characters to strcmp() instead of pointers to characters.
Here is more information regarding that function.
https://www.programiz.com/c-programming/library-function/string.h/strcmp

How to insert a continue statement inside an if statement

My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen.
I tried to look for a solution but the results doesn't fit for my program.
#include <stdio.h>
int main() {
int A, B;
char Y, N, C;
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2: ");
scanf ("%i", &A);
printf ("= %i", A + B);
printf ("\n\nAdd again? Y or N\n");
scanf ("%c", &C);
if (C == Y) {
//This should contain the code that will repeat the:
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2:
} else if (C == N)
printf ("PROGRAM USE ENDED.");
else
printf ("Error.");
}
You should just wrap your code inside a for loop:
#include <stdio.h>
int main() {
int A, B;
char Y = 'Y', N = 'N', C;
for (;;) { // same as while(1)
printf("Enter value 1: ");
if (scanf("%i", &B) != 1)
break;
printf("\nEnter value 2: ");
if (scanf("%i", &A) != 1)
break;
printf("%i + %i = %i\n", A, B, A + B);
printf("\n\nAdd again? Y or N\n");
// note the initial space to skip the pending newline and other whitespace
if (scanf(" %c", &C) != 1 || C != Y)
break;
}
printf("PROGRAM USE ENDED.\n");
return 0;
}
There are a lot of errors in your program.
Syntax error: please resolve it on your own.
There is no need for Y and N to be declared as character, you can use them directly as they are not storing any value.
NOW, there is no need for continue you can use while loop.
I have resolved your problem. Please take a look
Also, you are using a lot of scanf so there is an input buffer, a simple solution to it is using getchar() which consumes the enter key spaces.
#include <stdio.h>
int main()
{
int A, B;
char C = 'Y';
while (C == 'Y')
{
printf("Enter value 1: ");
scanf("%i", &B);
printf("\nEnter value 2");
scanf("%i", &A);
printf("= %i\n", A + B);
getchar();
printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}

C: With one variable entered wrong, my "incorrect input" if kicks in and doesn't let the user to finish typing in rest of variables

The problem is, basically, that if user enters a:5, b:f, everything works fine. But if it's the other way around and enters a letter to the 'a' variable, the program ends saying "Incorrect input", not letting the user to finish typing in rest of the variables. Why? Is it because of how I dealt with checking if the input is correct in the first place? How to "delay" the message and make it show after user finishes entering variables?
Here's the code:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
As Weather Vane already pointed out, the reason the program exits is, that when you enter a character (%c) and the scanf function is waiting for a integer (%d) it ignores the char, doesn't find an int but ends its' search on the '\n' (enter), so your variable l1 stays 0. This happens for all of your scanf calls, as it doesn't clear the buffer from characters that don't match.
Solving this
You can clear the input buffer, so that all the other scanf calls can get an actual input, though, you are still going to get an "Incorrect input" at the end.
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
printf("Number b: ");
l2 = scanf("%d", &b);
while (getchar() != '\n');
If you want to repeat the input process until a user enters the numbers correctly, you have to check the return value of the scanf in a while loop, something like this:
do {
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
} while (l1 != 1 || l1 != EOF);
Try this:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
getchar();
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
Reference : scanf() leaves the new line char in the buffer

Program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the factorial of n

The code is supposed to ask the user whether to find the sum of numbers from 1 to x or finding the factorial of x. After taking the user's input for the value of x, the program directly ends without running the if and else if statement. This is my code.
#include <stdio.h>
int sum(int num);
int fact(int num);
int main(void)
{
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x);
printf("Enter f for factorial, s for sum \n");
choice = getchar();
//These lines are ignored by C
if (choice == 'f' || choice == 'F')
{
printf("The factorial of %i is %i \n",x, fact(x));
}
else if (choice == 's' || choice == 'S')
{
printf("The sum from 1 to %i is %i \n",x, sum(x));
}
}
int sum (int num)
{
int sum =0;
for (int i =1; i <=num; i++ )
sum = sum+i;
return sum;
}
int fact (int num)
{
int fact =1;
for (int i =1; i <=num; i++ )
fact = fact*i;
return fact;
}
Can anyone please explain to me what is wrong with my code and how can I fix it? Thank you.
I think buffer problem. So, use
scanf(" %d", &x);
^^^
white-space
instead of
scanf("%d", &x);
and also, use
scanf(" %c", &choice);
instead of
choice = getchar();
The problem in this code is in getchar() function.
In first scanning : scanf("%d", &x); when user press enter key, it remain in the input buffer and the integer val is stored in variable x.
In second scanning: choice = getchar();, it reads the enter key in variable choice.
And you have written only two conditions:
if (choice == 'f' || choice == 'F')
else if (choice == 's' || choice == 'S')
That's why it is directly ending the code; as there is no code written for choice = other than 'f' and 's'
if you write 'else' part like this:
else printf("%d", choice);
It will print: 10 which is the ascii value of Enter / New line feed.
To avoid this, try to make following changes in your code:
int x = 0;
char choice;
printf("Enter a number : \n");
scanf("%d", &x); //here the integer is scanned in variable 'x'
choice = getchar(); //here the enter key is scanned in variable 'choice' so now input buffer is free
printf("Entr f for factorial, s for sum \n");
scanf("%c", &choice); //here the character entered by use will be stored in variable 'choice' so it is overwritten.

Program is printing late (c) [duplicate]

This question already has an answer here:
Why is C printing outputs late?
(1 answer)
Closed 7 years ago.
I wrote the following code (it is a caclulator which gets 1 of 3 operators (+/-/$) and 2 natural numbers (a,b) and calcultes (a op b) (a$b is defined to be a+(a+1)+...+(b-1)+b for a<=b and for a>b it is not defined):
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Please choose an operation (+/-/$): ");
char op;
scanf("%c", &op);
while (op != '+' && op != '-' && op != '$') {
printf("\nInvalid operation. Please choose again: ");
scanf("%c", &op);
}
int a;
int b;
char term;
printf("\nPlease enter the first operand: ");
int scanCheck = scanf("%d%c", &a, &term);
while (scanCheck != 2 || term != '\n' || a < 0) {
printf("\nInvalid number\n. Please enter the first operand: ");
scanCheck = scanf("%d%c", &a, &term);
}
printf("\nPlease enter the second operand: ");
scanCheck = scanf("%d%c", &b, &term);
while (scanCheck != 2 || term != '\n' || b < 0) {
printf("\nInvalid number\n. Please enter the first operand: ");
scanCheck = scanf("%d%c", &b, &term);
}
if (op == '$' && a > b)
printf("\nThe result is: Not Valid");
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '$':
result = 0;
while (a <= b) {
result += a;
a++;
}
break;
}
printf("\nThe result is: %d", result);
return 0;
}
My problem is that when I run the program it prints nothing. However, after giving the program an input (e.g +, 3, 4) it prints the lines it should have printed earlier (with the correct result). Why does this happen? How can I fix this? FYI I'm using eclipse Juno with minGW compiler.
You may want to add the '\n' at the end of your print statements instead of at the beginning: the buffers may not be flushed and will be delayed because of it.
Output is line buffered. Add a newline at the end of any printout. Or flush the buffer explicitly using fflush(stdout);
For some reason many C programmers like to print newlines at the start of each printout. My advice would be not to do it that way. Just put the newline at the end of each printout, and you'll save yourself lots of trouble:
printf("The result is: %d\n", result);

Resources