How do I add a loop for scanf in C? - c

I have a short question:
How can I expand my program so that it checks if I entered the right format?... if not the program should repeat the scanf.
This is how far I came:
#include <stdio.h>
int main()
{
float zahlen[2];
int i = 0;
while (i < 2 && zahlen != EOF) {
printf("%d. Zahl", i + 1);
scanf_s("%f", &zahlen[i]);
}
printf("Division: %f\n", zahlen[0] / zahlen[1]);
printf("Produkt: %f\n", zahlen[0] * zahlen[1]);
printf("Summe: %f\n", zahlen[0] + zahlen[1]);
printf("Diffenrenz: %f\n", zahlen[0] - zahlen[1]);
printf("Mittelwert: %f\n", (zahlen[0] + zahlen[1]) / 2);
getchar();
return 0;
}
Would appreciate any help of you. Have a nice day/night.

You should define what a right format is. But in a form of pseudo-code
float input;
// First get the input
do {
sacnf_s("%f", &input);
} while (!IsRightFormat(input)); // If the input was not correct get it again
// Do your stuff here
// ...

Related

C while loop is printing extra number

Can someone help me. My code is printing an extra number
It's suppose to work like this:
if is N=38
then it's suppose to print
32.0
33.8
35.6
37.4
but mine prints
32.0
33.8
35.6
37.4
39.2
how do i get rid of the last number. I'm still a beginner so i'm quite bad at this
#include<stdio.h>
int main(){
int i, n;
float f;
printf("toogoo oruulna uu: ");
scanf("%d", &n);
i=0;
while (f<=n){
f = (9.0/5.0 * i) + 32;
printf("%.1f\n", f);
i++;
}
return 0;
}
A quick fix
while (1){
f = (9.0/5.0 * i) + 32;
if(f>n) // Move condition to after calculation
break;
printf("%.1f\n", f);
i++;
}
This will also solve the bug that you're using f before it's initialized.
You can do this:
#include<stdio.h>
int main(){
int i, n;
float f;
printf("toogoo oruulna uu: ");
scanf("%d", &n);
i=0;
f=0;
while (f<=(n-1)){
f = (9.0/5.0 * i) + 32;
printf("%.1f\n", f);
i++;
}
return 0;
}
Look while (f<=(n-1)) , the while loop will stop 1 iteration earlier and make sure you are setting the f variable with a value before you use it!

If statement isn't being caught

I can't for the life of me figure out why C is ignoring my if statement.
I'm trying to skip all the procedures in the while statement when the input is -1000 (so that it doesn't print before exiting the program). Here is my code:
int main()
{
int count = 1;
int grade1;
int grade2;
double sum;
double average;
printf("Please input a number of grades: \n");
scanf("%d", &grade1);
printf("Sum is: %d.000000 \n", grade1);
printf("Average is: %d.000000 \n", grade1);
count++;
sum = grade1;
while(grade2 != -1000)
{
if(grade2 != -1000)
{
scanf("%d", &grade2);
sum = sum + grade2;
average = sum / count;
printf("Sum is: %lf \n", sum);
printf("Average is: %lf \n", average);
grade1 = sum; //Converting the sum back into an int
count++;
}
}
return 0;
}
Here is a link to an image of my output. As you can see, even when grade2 is given -1000, the if statement is ignored, and another 2 lines are printed to the screen before the program exits. How can I fix this? Is this some sort of oddity of how C works?
When you do this the first time
while(grade2 != -1000)
the variable grade2 is uninitialized.
Consequently your code has undefined behavior
Make sure to initialize it like:
int grade2 = 0; // To zero or whatever you want
Further - always check the value returned by scanf. So instead of
scanf("%d", &grade1);
do
if (scanf("%d", &grade1) != 1)
{
// Add error handling here
}
Your next problem is that you don't scan grade2 before checking whether it is -1000. Move the scan before the if-statement.
Maybe what you want to do is:
int grade2 = 0;
while(grade2 != -1000)
{
if (scanf("%d", &grade2) != 1)
{
// Add error handling here
}
if(grade2 != -1000)
{
...
so that you scan for the first grade2 before you do the if(grade2 != -1000) and enters the calculation code
Written differently this could be:
while(1)
{
if (scanf("%d", &grade2) != 1)
{
// Add error handling here
}
if(grade2 == -1000) break; // Terminate the while
sum = sum + grade2;
....
While it's true that grade2 should be initialized and the return for scanf() should be checked, that's not the main problem the poster is running into. The problem is that he checks
if(grade2 != -1000)
AFTER he has already processed grade2. He should move
scanf("%d", &grade1);
before
if(grade2 != -1000)
The if statement in your while loop is redundant because, the loop will not iterate unless the condition that controls it is true, and the if statement comes directly after that, checking for the same condition, whilst grade2 is unchaged.
Instead, you need to move it to after the scanf() call because that will modify the variable grade2, and don't forget to initialize your variables before using them or else you'll have undefined behavior.
int main(void)
{
//....
int grade2 = 0; // initialized...
//....
while (grade2 != -1000)
{
scanf("%d", &grade2);
if (grade2 != -1000)
{
sum = sum + grade2;
average = sum / count;
printf("Sum is: %lf \n", sum);
printf("Average is: %lf \n", average);
grade1 = sum; //Converting the sum back into an int
count++;
}
}
}

Calculating the result of a power and a base without math.h

At my university I was asked to create a program that asks the user for two inputs. One is the base and the other is the power of a number. I am not allowed to use math.h only loops.
This is my code thus far:
#include <stdio.h>
int main() {
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
for(reps = base; reps <= power; reps += 1) {
printf("* %d ", base);
}
for(number; number <= power;number += 1) {
int result = base * base;
for (result; number <= power; result = base * result) {
result = result * base;
printf("\n or %d", result);
}
}
return 0;
}
Please help me. I am so lost and I feel like crying :( not that it matters.
(Your main issue is that you are using an uninitialised variable; the behaviour of doing that in C is undefined.)
But let's rework the answer. The first thing to do is to separate the actual power function from all the input and output. With regards to that function, I'll put my favourite way into the answer pool on the understanding that you'll work through it carefully and understand it.
You can ace this problem using a technique called exponentiation by squaring:
int getPower(int base, int power/*must be non-negative*/)
{
int ret = 1;
while (power){
if (power & 1){ /*this means the current value of `power` is odd*/
ret *= base;
}
power >>= 1; /*ToDo - figure this out with your debugger*/
base *= base;
}
return ret;
}
The method is adequately explained in https://en.wikipedia.org/wiki/Exponentiation_by_squaring
The loop for calculating the power looks like this
int product = 1;
for(int multiplicationCounter = 1;multiplicationCounter <= power; multiplicationCounter ++) {
product *= base;
}
printf("Result is %d", product);
You can integrate this in your code, maybe change the output.
This should replace your whole second for-loop.
assume both base and power is positive integer,
then
int Result =1;
for (int i=0; i<=power;i++)
{
if(power==0)
Result=1;
Result =Result*base;
}
This should work
#include <stdio.h>
int main()
{
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
int result=1:
for(number=1; number <= power;number += 1)
{
result=result*base
}
printf("The result is %d", result);
return 0;
}

How to make compiler repeat until the number 0 is presed

I'm wondering how to make the compiler repeat itself if the user presses a random button at the end. But if the user presses "0" the compiler exits.
My code:
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <float.h>
struct mystruct
{
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
struct mystruct data;
float max = 0;
float min = FLT_MAX;
float sum = 0;
float avg = 0;
int i = 0;
float resultat = 0;
printf("Startnummer: \n");
scanf_s("%f", &data.startnummer);
printf("Hoppnummer:\n");
scanf_s("%f", &data.hoppnummer);
printf("Svarighetsgrad:\n");
scanf_s("%f", &data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("domarpoang %d\n", i + 1);
float f;
if (scanf_s("%f", &f) == 1)
{
if (f < min) min = f;
if (f > max) max = f;
data.domarpoangs[i] = f;
}
else
{
printf("error parsing float\n");
exit(0);
}
}
system("cls");
printf("Startnummer: %.1f \n", data.startnummer);
printf("Hoppnummer: %.1f\n", data.hoppnummer);
printf("Svarighetsgrad: %.1f\n", data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("Domarpoang %d: %.1f\n", (i + 1), data.domarpoangs[i]);
}
for (i = 0; i < 7; i++)
{
sum += data.domarpoangs[i];
}
sum = sum - (max + min);
avg = sum/5;
resultat = avg * 3 * data.svarighetsgrad;
printf("Hoppoang:%.2f \n", resultat);
printf("Tryck tangent for nytt hopp!");
getchar();
getchar();
return 0;
}
*If the user presses random button, the compiler repeat itself from the beginning
*If the user presses 0, the compiler exits.
Any help is appreciated, thank you.
This answer puts a loop around the body of your main() code, taking care to re-initialise some of the variables for the next iteration.
There are many SO questions about getting keyboard input and clearing the debris. I know of no simple standard ways of testing for keyboard input such as kbhit(), for taking a single key input such as getch() or for flushing the input. Even getchar() is horrible - it won't return until you have pressed "Enter" which it leaves in the input buffer. This has resulted in many SO answers with impenetrable (to me) formats for scanf() to flush the input, or testing if (getchar() == EOF) - which does not respond to the "Enter" key.
So I have put a simple wrapper around the main() code, which terminates when '0' is entered followed by a control char (because fgets() appends the newline) or terminator. This removes the need to clean up the input - except in the case where the user inputs some silly typing. GIGO!
#include <stdio.h>
#include <float.h>
#define BUFFSIZE 10
struct mystruct {
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
char kbuff [BUFFSIZE+1];
struct mystruct data;
float max;
float min;
float sum;
float avg;
int i;
float resultat;
do {
max = 0; // initialise for each loop
min = FLT_MAX;
sum = 0;
printf ("Body of your main loop\n");
fgets(kbuff, BUFFSIZE, stdin);
} while (kbuff[0] != '0' || kbuff[1] >= ' ');
return 0;
}

C - Loop, <math.h>, and float

#include <stdio.h>
#include <math.h>
int main()
{
int i;
int result;
float f;
while((result = scanf("%d", &i)) != EOF)
{
scanf("%f", &f);
printf("%.0f %.0f %.0f\n", floor(f), round(f), ceil(f));
}
printf("Done.\n");
return 0;
}
Hi,
I just began with C and I'm having a problem solving a question.
The problem is that with the user input, I need to get three sets of numbers that are floored, rounded, and ceiled. This process must be ongoing until the user stops by EOF command (Ctrl-D).
When I run my code above, input a value 3.1415, I get 0 0 1 as an output, which is wrong because it's supposed to be 3 3 4.
Any suggestions or help on how to fix the problem would be appreciated.
According to your code, you first need to input an integer value and then enter a float value.
OR, you can start accepting float value like this:
#include <stdio.h>
#include <math.h>
int main()
{
int result;
float f;
while((result = scanf("%f", &f)) != EOF)
{
printf("%.0f %.0f %.0f\n", floor(f), round(f), ceil(f));
}
printf("Done.\n");
return 0;
}
According to your code you need to input integer first then float, But if you enter float value first, that value read by i first and return 0 that is !=EOF, so second scanf does not wait for input, because it is inside the while loop. So always you will get 0 0 1 for all inputs!
To scan a number inside while loop use-
if (scanf("%f", &f) == 0) {
printf("Err. . .\n");
do {
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
Else scan float value first instead of int and float. Try this code-
while((result = scanf("%f", &f)) != EOF)
{
printf("%.0f %.0f %.0f\n", floor(f), round(f), ceil(f));
}
printf("Done.\n");

Resources