Why scanf is not working in functions using C programming? [duplicate] - c

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 1 year ago.
I wrote this C program using 2 functions, but in this first case grade() is not prompting for the input:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Function Type 2\n");
x = motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y = grade();
printf("\nReturned value is %c\n", y);
}
int motivQuote()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n == 1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n == 2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n + 2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade, 1);
return grade;
}
And here in the second case, grade() prompts for the input only in the second call, but the first one is not working:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Functions\n");
x= motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y= grade();
printf("\nSubject2: ");
z= grade();
printf("Returned values are %c and %c\n", y, z);
}
int motivQuote ()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n==1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n==2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n+2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade,1);
return grade;
}
Can anyone tell me what's the reason please?

Use scanf(" %c",&grade,1); with a space before %c. This will solve the problem.

Related

No output in C program

This my first program of C programming using recursive functions, it calculates the sum of the first n natural numbers. I am not able to get an output from it, it asks for the number but after that the program doesnt respond, can someone please help me out?
int n();
int main(){
int num;
printf("Enter num:\n");
scanf("%d", &num);
n(num);
printf("The sum of %d is: %f", num, n(num));
return 0;
}
int n(int x){
if (x != 0){
return n(x) + n(x-1);
**strong text** }
else{
return x;
}
}
Firstly, in the recursive function, return n(x) + n(x-1); should have been return x + n(x-1); as in the first case, n(x) will continuously make a called to another n(x), therefore making an infinite loop, or, more formally, return a 0xC00000FD exception, a Stack Overflow exception.
Also, in the last printf() function, %f should have been %d:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %d", num, n(num));
return 0;
}
Using %f to print an integer will caused an undefined behavior, because %f is a float format specifier, as noted here.
If you really want to convert it to a float:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %f", num, (double) n(num));
return 0;
}
*Note: Ran on Code::Blocks 20.03, Windows 10 64bit.
More info on format specifiers : https://www.tutorialspoint.com/format-specifiers-in-c
It should be return x instead of calling the same function,
you can use type conversion for changing the integer into a float,
int n();
int main(){
int num,x;
printf("Enter num:\n");
scanf("%d", &num);
x=n(num);
printf("The sum of %d is: %f", num, float(x));
return 0;
}
int n(int x){
if (x != 0){
return x + n(x-1);
**strong text** }
else{
return x;
}
}

Why isn't the calculator I'm coding with C working?

I am pretty new to C, and am working on a pretty big project. I am trying to make a calculator, and so far I only have the addition. They way it works is that it asks for how many numbers they want in the addition statement, and then I use a while() loop to try to get all the info. Just some side info - I am using the Cygwin terminal on a Windows 10 operating system.
#include <stdio.h>
int main(){
char Etype;
printf("Hello! Welcome to your virtual calculator!\n");
printf("Press 'a' for addition!\n");
scanf("%c", &Etype);
if(Etype == 'a' || Etype == 'A') {
int Anum;
int x = 1;
int y;
printf("How many numbers do you want in this addition statement?\n");
scanf("%f", &Anum);
while(x < Anum) {
printf("Emter number %d\n", x);
scanf("%d", &y);
x = x + 1;
}
}
}
whenever I answer how many numbers I want on my statement, nothing happens. I hope you can help, and if so thank you!
At the very least, you should either look at the compiler warnings, or get a better compiler and look at the compiler warnings.
clang-7 -pthread -lm -o main main.c
main.c:16:29: warning: format specifies type 'float *' but the argument has type
'int *' [-Wformat]
scanf("%f", &Anum);
~~ ^~~~~
%d
1 warning generated.
Perhaps you just forget to summary the answer.
To input an integer, you should use %d instead of %f.
What's more, x should be initialized with 0.
You can edit your codes as:
#include <stdio.h>
int main(){
char Etype;
printf("Hello! Welcome to your virtual calculator!\n");
printf("Press 'a' for addition!\n");
scanf("%c", &Etype);
if(Etype == 'a' || Etype == 'A') {
int Anum;
int x = 0; // count from 0
int y;
int sum = 0; // to summary the answer
printf("How many numbers do you want in this addition statement?\n");
scanf("%d", &Anum); // use %d to input integer
while(x < Anum) {
printf("Emter number %d\n", x);
scanf("%d", &y);
sum += y; // summary
x = x + 1;
}
printf("Answer: %d\n", sum); // print the answer after calculation
}
}
Or a clearer version:
#include <stdio.h>
int main(){
char eType[2];
printf("Hello! Welcome to your virtual calculator!\n");
printf("Press 'a' for addition!\n");
scanf("%s", eType);
if(eType[0] == 'a' || eType[0] == 'A')
{
int n, sum = 0;
printf("How many numbers do you want in this addition statement?\n");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int x;
printf("Enter number %d\n", i);
scanf("%d", &x);
sum += x;
}
printf("Answer: %d\n", sum);
}
}

Using a loop to run a program n amount of times

I am new to the C programming language. I am attempting to run the code below an N amount of times (based on the user input of "Enter amount of iterations"). I am trying to do this using a for loop (also tried with a while loop) but have been unsuccessful.
Whenever I run the code below, my terminal continuously repeats "Enter two float numbers:". I have to close the terminal and reopen it to try again. Does the issue have to do with my for loop? I am interpreting my for loop as: "a=0; if a > 0; increment a". Is there a way I can set a limit for "if a > 0" or should I be using a while loop? If the user enters "3" for amount of iterations, I am expecting the program to ask "Enter two float numbers" 3 times (with the answer).
float sum (float m, float n){
return m+n;}
int main() {
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i; i < 0; i++) {
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x,y);
printf("%f and %f = ", x, y);
printf("%f\n", su);}
return 0;}
CORRECT ANSWER Formatted for readability:
float sum(float m, float n)
{
return m + n;
}
int main()
{
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
This should behave more like you would like it to:
#include <stdio.h>
static float sum(float m, float n)
{
return m + n;
}
int main(void)
{
float x, y;
int a;
printf("Enter amount of iterations: ");
if (scanf("%d", &a) != 1)
{
fprintf(stderr, "Invalid input for iterations\n");
return 1;
}
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
if (scanf("%f %f", &x, &y) != 2)
{
fprintf(stderr, "Failed to read to floating point numbers\n");
return 1;
}
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
Note that it checks that the input operations are successful, and reports errors on standard error (stderr). The code uses a standard C for loop to count from 0 up to a limit — this is idiomatic C. You should get used to using it.
As I noted in a comment, the a in the for loop is different from and unrelated to the a declared earlier in your code and set by the input operation. The a in the for loop is not initialized; you can't tell how many times the loop will be executed. A good compiler should warn you about redefining or shadowing a.
for (i = 0; i < a; i++); - answer provided by J.S!

Scanf is being ignored [duplicate]

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 7 years ago.
#include <stdio.h>
#define length 20
main()
{
float x;
int y;
float array1[length], array2[length], array3[length];
float ray[length];
int size1 = insert(array1, length);
printf("enter number: ");
scanf("%d", &y);
int size2 = insert(array2, length);
int size3 = insert(array3, length);
}
int insert(float a[], int size)
{
int n = 0;
while(n<size && scanf("%f\n", &a[n]) == 1)
{
printf("you entered: ");
printf("%2.1f\n", a[n]);
n++;
}
return n;
}
When I run the program, it executes the first insert okay, but the next time function is called, scanf() seems to be ignored completely. I tried putting it right after where insert is done, but that's ignored as well.
Use %*c in scanf to consume the newlines along with space around %d in the scanf in main(). I tested the below code on MingW and it seem to work. The '\n' in your scanf is being consumed making it scanf() return while the '\n' at the press of enter key still remains in IO buffer to be consumed by scanf() again; hence the weird behaviour.
#include <stdio.h>
#include <stdlib.h>
#define length 20
int insert(float *a, int size)
{
int n = 0;
while(n<size && scanf("%f%*c", &a[n]))
{
printf("you entered: ");
printf("%2.1f\n", a[n]);
n++;
}
return n;
}
int main(int argc, char* argv[])
{
float x;
int y;
float array1[length], array2[length], array3[length];
float ray[length];
int size1 = insert(array1, length);
printf("enter number: ");
scanf("%d", &y);
int size2 = insert(array2, length);
int size3 = insert(array3, length);
return 0;
}
In the scanf format string, change "%f\n" to "%f". The \n in a scanf format string does not mean "wait for newline".
You do not need to worry about waiting for newline, because the only format specifiers you use are %f and %d, which both discard any leading whitespace.

Can't nail the problems with this code

Ok so I got this thing going here.
I keep getting a few errors.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
//functions called
int get_lmt();
int get_total_trash();
void print_output(int, int);
//why is it void?
int main(void)
{
char hauler[100];
int t_trash=0, lmt=0;
printf("Hello \n What is your name: ");
fflush(stdin);
scanf("%s", &hauler);
t_trash = get_total_trash();
lmt = get_lmt();
printf("Name: %s\n", &hauler);
print_output(lmt, t_trash);
system("pause");
return 0;
}
int get_total_trash()
{
char yn = 'y';
int t_trash = 0, trash=0;
while (yn != 'n')
{
printf("What is your trash: ");
fflush(stdin);
scanf("%i", &trash);
t_trash = trash + t_trash;
printf("Do you have more trash tons? (y or n): ");
fflush(stdin);
scanf("%c", &yn);
}
return t_trash;
}
int get_lmt()
{
int lmt = 0;
printf("What was last months trash: ");
fflush(stdin);
scanf("%i", &lmt);
return lmt;
}
void print_output(int lmt, int t_trash)
{
float rate = 350.00, charge;
int sum=0, total=0;
if (lmt > t_trash)
{
printf("Total trash tons: %i\n", &t_trash);
printf("Last month's trash: %i\n", &lmt);
printf("Rate: $ %.2f\n", &rate);
}
else
{
printf("What is your tonnage rate: ");
fflush(stdin);
scanf("%.2f\n", &charge);
sum = t_trash - lmt;
total = sum * charge;
rate = rate + total;
printf("Total trash tons: %i\n", &t_trash);
printf("Last month's trash: %i\n", &lmt);
printf("Rate: $ %.2f\n", &rate);
}
}
Now what it should be doing is, The main should be calling the functions on screen as needed.
Now i did all of this with cout cin and it works fine no problems. But when I run this (this is modified to the printf and scanf) it says:
OK UPDATE: Got a ton of it to work. Just one more thing and I should be good. The outcome will not go as expected.
Instead of an output of
last months trash: 100 (asked at the end of the loop)
trash tonnage: 50 (accumulated in the loop)
rate: 350.00 (float variable)
(this is if last month trash was > this month.)
I get just bad numbers all around. It makes no mathematical sense.
Other then that it works fine.
Does the code the the last function look wrong to you guys?
Lots of problems with this code. Lots of them.
1) print_output defintiion takes in a char[100] (char*), print_output declatation takes a char
2) When you pass hauler into print_output, you are passing in hauler[100] (a char, and one pass the end of the array to boot)
3) printf("Name: %s\n", &hauler); hauler is of type char[100] (char*), so &hauler is char**.
there is probably more.

Resources