C Program Issue: scanf isn't working properly - c

The program below is supposed to demonstrate using an array of pointers to functions. Everything works great, except the scanf statements that change the value of num1 and num2 (I have them commented in the code). If I initialize the variables and have them equaling, say, 2, then when I run the program their value's will be 2 regardless of what I enter in scanf to replace the value. Any help with this would be greatly appreciated!
#include <stdio.h>
// function prototypes
void add (double, double);
void subtract (double, double);
void multiply (double, double);
void divide (double, double);
int main(void)
{
// initialize array of 4 pointers to functions that each take two
// double arguments and return void.
void(*f[4])(double, double) = { add, subtract, multiply, divide };
double num1; // variable to hold the 1st number
double num2; // variable to hold the 2nd number
size_t choice; // variable to hold the user's choice
printf("%s", "Which operation would you like to perform on the two numbers?\n");
printf("%s", "[0] add\n");
printf("%s", "[1] subtract\n");
printf("%s", "[2] multiply\n");
printf("%s", "[3] divide\n");
printf("%s", "[4] quit\n");
scanf_s("%u", &choice);
// process user's choice
while (choice >= 0 && choice < 4)
{
printf("%s", "Enter a number: ");
scanf_s("%f", &num1); // <--- THIS SCANF_S STATEMENT ISN'T CHANGING NUM1'S VALUE
printf("%s", "Enter another number: ");
scanf_s("%f", &num2); // <--- THIS SCANF_S STATEMENT ISN'T CHANGING NUM2'S VALUE
// invoke function at location choice in array f and pass
// num1 and num2 as arguments
(*f[choice])(num1, num2);
printf("%s", "Which operation would you like to perform on the two numbers?\n");
printf("%s", "[0] add\n");
printf("%s", "[1] subtract\n");
printf("%s", "[2] multiply\n");
printf("%s", "[3] divide\n");
printf("%s", "[4] quit\n");
scanf_s("%u", &choice);
} // end while loop
puts("Program execution completed");
} // end main
void add(double a, double b)
{
printf("%1.2f + %1.2f = %1.2f\n", a, b, a + b);
}
void subtract(double a, double b)
{
printf("%1.2f - %1.2f = %1.2f\n", a, b, a - b);
}
void multiply(double a, double b)
{
printf("%1.2f * %1.2f = %1.2f\n", a, b, a * b);
}
void divide(double a, double b)
{
printf("%1.2f / %1.2f = %1.2f\n", a, b, a / b);
}

As others have said, use the correct format specifiers.
1) When using scanf(), "%f" is for float and "%lf" is for double.
double num1;
// scanf_s("%f", &num1);
scanf_s("%lf", &num1);
2) The use of "%u" may work given your platform, but size_t and unsigned are not necessarily the same size. With C11, (and maybe C99) use the z modifier.
size_t choice;
// scanf_s("%u", &choice);
scanf_s("%zu", &choice);
3) It is always good to check the result from scanf_s().
if (1 != scanf_s(...)) {
; // handle_error();
}

Related

Integer prints out as 0 in C when putting 1 in

I think this is a really stupid question. I just started with C and made this little "calculator":
#include <stdio.h>
#include <stdlib.h>
int main() {
while(1) {
int a;
int b;
char op;
printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
printf("Enter the operator: ");
scanf("%s", &op);
switch(op) {
case '+':
printf("%d + %d = %d", a, b, a + b);
break;
case '-':
printf("%d - %d = %d", a, b, a - b);
break;
case '*':
printf("%d * %d = %d", a, b, a * b);
break;
case '/':
printf("%d / %d = %d", a, b, a / b);
}
printf("\n");
char cont;
printf("Do you want to continue? (y/n): ");
scanf("%s", &cont);
if(cont == 'n') {
break;
}
}
return 0;
}
But when I run it and try to put in "1" and "1" it puts out the wrong number:
Enter the first number: 1
Enter the second number: 1
Enter the operator: +
1 + 0 = 1
Do you want to continue? (y/n): n
This is probably some dumb problem but I don't get it xD
You're reading the operator as a string, yet 'op' is a single char.
As a result, the terminating '\0' is written to the next byte in memory, which in this case is the first byte of the variable 'b' ('b' and 'op' are both on the stack).
As a fix I would suggest:
make 'op' a char array of size 2
use fgets to ensure that only 1 byte is read
char op[2] = {0};
fgets(op,2,stdin);

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

How do I keep my program asking me info until I tell him to stop?

Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}

Please help me spot my error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey I am writing a simple program that adds fractions.
but whenever i run the program it will not perform the operations.
It only scans the input, but no output.
please spot my error! >>>>>>CANNOT USE FLOATS<<<<<<<<
#include <stdio.h>
int main ( void )
{
int lcd, d1, d2, num1, num2, sum;
printf("Enter the first number:");
printf("Enter the numerator:");
scanf("%d", num1);
printf("Enter the denominator:");
scanf("%d", &d1);
printf("Enter the second number:");
printf("Enter the numerator:");
scanf("%d", &num2);
printf("Enter the denominator:");
scanf("%d", &d2);
for (lcd = d1; lcd % d2 != 0; lcd+= d1);
num1 *= lcd / d1;
num2 *= lcd / d2;
sum = num1 + num2;
printf("%d", sum);
return 0;
}
scanf must receive pointers
scanf("%d", num1) -> scanf("%d", &num1)
Because scanf use call by reference. What is that? please see the following code.
#include <stdio.h>
void foo(int i)
{
i = 1;
}
void bar(int *pi)
{
*pi = 1;
}
int main()
{
int a = 2;
foo(a);
printf("%d", a); /* output is 2 */
bar(&a);
printf("%d", a); /* output is 1 */
}
In foo(a), we're using call by value. That means a is copied when we call foo. the code, i = 1, of foo changes only the copy of a, and does NOT change real value of a.
In bar(&a), we're using call by reference. Can you find the difference? Yes, it's bar(&a), not bar(a). "&" operator gets the pointer of a, and we call bar with the pointer. So pi refers to a, and *pi = 1 changes real value of a successfully.
A real-life example is here: printf and scanf.
int i = 0;
printf("output number : %d\n", i);
scanf("%d", &i); /* input number */
printf doesn't need to change its arguments, so it use call-by-value.
But, scanf receives user's input and change its arguments into user's input. so it use call-by-reference. thus, we should use &i, not i.
Does it need to be that complex? Why not just divide the numerator by the denominator?
Also, your working with integers. I think you want floats.
#include <stdio.h>
int main ( void )
{
int d1, d2, num1, num2;
printf("Enter the first number:");
printf("Enter the numerator:");
scanf("%d", &num1);
printf("Enter the denominator:");
scanf("%d", &d1);
printf("Enter the second number:");
printf("Enter the numerator:");
scanf("%d", &num2);
printf("Enter the denominator:");
scanf("%d", &d2);
printf("%f",
((float) num1 / (float) d1) + ((float) num2 / (float) d2)
);
return 0;
}
If you want to compute the non simplified sum of two fractions, just using the following formula
a/b + c/d = (a*d + c*b)/(b*d)
Therefore, the following code could be used to achieve your goal
#include <stdio.h>
int main ( void )
{
int den1, den2, num1, num2, sum_num, sum_den;
printf("Enter the first number:\n");
printf("\tEnter the numerator:");
scanf("%d", &num1);
printf("\tEnter the denominator:");
scanf("%d", &den1);
printf("Enter the second number:\n");
printf("\tEnter the numerator:");
scanf("%d", &num2);
printf("\tEnter the denominator:");
scanf("%d", &den2);
sum_num = num1 * den2 + num2 * den1;
sum_den = den1 * den2;
printf("sum = %d/%d\n", sum_num, sum_den);
return 0;
}

What's wrong with this C program?

I've written a special calculator which prompts the user for 2 numbers then displays a menu which basicly asks the user what to do with that input. It works great however no matter what numbers I input the result is 0. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
char a, rad, patrat;
float x, y, media, radical, pat1, pat2;
patrat = 253;
rad = 251;
loop:
printf("Input 2 numbers...\n");
scanf("%f %f", &x, &y);
media = (x+y)/2;
radical = sqrt(x+y);
pat1 = x*x;
pat2 = y*y;
loop2:
printf("\n \nA - Arithmetic media.\n");
printf("B - Square root.\n");
printf("C - Sqare of the 2 numbers.\n");
printf("D - Write other numbers.\n");
printf("E - Terminate the program.\n");
a = getch();
switch(a) {
case'a':
system("cls");
printf("Media of the 2 numbers is %f", &media);
goto loop2;
case'b':
system("cls");
printf("%c%f + %f = %f", &rad, &x, &y, &radical);
goto loop2;
case'c':
system("cls");
printf("%f%c = %f, %f%c = %f", &x, &patrat, &pat1, &y, &patrat, &pat2);
goto loop2;
case'd':
goto loop;
case'e':
return 0;
}
}
You're using & in your printf statements, you shouldn't be. Scanf has it as it's writing so takes pointers.
Why are you using the operator & to your printf arguments?
printf doesn't take pointer arguments for %f conversion specification
float b;
scanf("%f", &b);
but
float a = 42;
printf("%f\n", a);
printf("Media of the 2 numbers is %f", &media);
should be
printf("Media of the 2 numbers is %f", media);
similarly for all other printf()
Generally goto statements are considered harmful when they are called backwards! So please avoid them. The same functionality can be done by a while(1) for for(;;) loop with proper termination condition.
In your printf statement, you are using
printf("Media of the 2 numbers is %f", &media);
&media is the address of your variable media.
In scanf, we provide the address of the variable as parameter so that it stores the values at that address. But in printf, we provide the variable value and not the variable address. If you provide variable address then it would print the address and not the value.
So the correction should be
printf("Media of the 2 numbers is %f", media);

Resources