In C: 2 printf output when all I want is one. - c

This program is supposed to balance an account by asking for original amount then asking what sort of transaction they would like. The printf call is called twice when all I want is one. output: "Enter transaction: Enter transaction: ". Otherwise works fine. code:
#include <stdio.h>
int main(void)
{
float amount, old, new;
char letter;
printf("Please enter your current balance: ");
scanf("%f", &old);
printf("Enter the kind of transaction you would like: W - withdrawl, D - deposit, F - finished. \n");
scanf("%c", &letter);
while (letter != 'F'){
if (letter == 'D'){
printf("Amount: ");
scanf("%f", &amount);
new = old + amount;
old = new;
}
if (letter == 'W'){
printf("Amount: ");
scanf("%f", &amount);
new = old - amount;
old = new;
}
printf("Enter transaction: ");
scanf("%c", &letter);
}
if (letter == 'F')
printf("Your ending balance is %f.\n", old);
return 0;
}
Would greatly appreciate any insight! Thank you!!

scanf(" %c", &letter); instead of scanf("%c", &letter);
the original (without space) would interpret Enter as an input.

You may also be able to solve the issue by clearing the input (previous Enter press) from stdin input buffer. Add this line
fflush(stdin);
before
scanf("%c", &letter);
However, the solution provided by #artm is recommended, mine might not work depending on platform.

Related

One more question about using a while to "embrace" my code instead of calling main()

So, in this link -> Problems doing a while loop I did a question about a problem dealing with the use of while instead of calling main(), and it helped me, my code worked, but there's a new little problem. I'mma show it with a kind of "Dice Roller Code"
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
srand((unsigned)time(NULL));
int totalSides, dice, modifier;
char c, d;
printf("Welcome to the dice roller!\n");
printf("If you wanna roll the dice, press 'r'. If you wanna quit, press 'q': ");
scanf(" %c", &c);
while(c == 'r'){
printf("How many sides does the dice you want to roll have? Answer with a int number: ");
scanf("%d", &totalSides);
printf("Do you need any modifier? Press 'a' to add, press any other key to dispense: ");
scanf(" %c", &d);
if(d == 'a'){
printf("Insert your modifier value: ");
scanf("%d", &modifier);
printf("\n");
}
dice = rand() % totalSides + 1;
printf("You've got a %d!\n", dice);
if(d == 'a'){
printf("But you've got a %d modifier...\n", modifier);
dice = dice + modifier;
printf("Then, you got a %d!", dice);
}
printf("\n\n\n\n");
repeat();
c = repeat();
printf("\n\n\n\n");
}
}
int repeat(){
char c;
printf("Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: ");
scanf("%c", &c);
return c;
}
The program works very well, but in the output I got the same sentence two times, like:
"Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: "
How can I solve this?
You are calling repeat twice, so therefore it is printing twice.
repeat();
c = repeat();
Try replacing the first call to repeat to getchar(). This will consume the character entered after the modifer line.
getchar();
c = repeat();
It looks like you are just starting to learn C, and it might be worthwhile to read a book on the matter. One that I can recommend is Modern C. It's available free online, or you can buy a print version.

C language: The Array did not return a correct value

I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])

Getting one loop for multiple characters using "while"

I'm new on Stackoverflow and I'm very, completely new to coding. Just messing around with C. Here's what I'm trying to do here (don't take this program scientifically accurate), this is a program that calculates for special relativity equations of length, mass and time. I have 3 questions actually:
When I try to put other characters in the y/n questions, everything works but for example if I enter "sfkl", the warning comes up 4 times because I entered 4 characters. And if I put space, it doesn't even give a warning until I put another character and then enter. Can I make it give 1 warning no matter how many characters I enter in one line (including space)?
My other question is, I kind of prevented inputting anything other than y/n but for the double value inputs (mass, length and time), I can't figure out a similar system (asking for a double value over and over again). Can you suggest me a solution?
And my third question is, when doing "scanf_s(" %c", &answer);", if I don't put a space before "%c", it doesn't work properly. It registers an enter and asks me to enter y/n only. Why need a space before that?
Here's the code:
#include <stdio.h>
#include <math.h>
#define LIGHT 299792458
int input();
int main()
{
printf("\n\n\tThis program calculates how length, mass and time changes with respect to your speed.\n\n\tThe values you enter are the quantites which are observed by a stationary observer and the output values are the quantites observed by the person in a vehicle which is moving at the speed that you enter.");
input();
return 0;
}
int input()
{
double length, mass, utime, speed;
char answer;
do
{
printf("\n\n **************************************************");
printf("\n\n\tPlease enter a quantity of length: ");
scanf_s("%lf", &length);
printf("\n\tPlease enter a quantity of mass: ");
scanf_s("%lf", &mass);
printf("\n\tPlease enter a quantity of time: ");
scanf_s("%lf", &utime);
printf("\n\tNow enter the speed of the vehicle (m/s): ");
scanf_s("%lf", &speed);
while (speed > LIGHT)
{
printf("\n\n\tNothing can surpass the speed of light in the universe. Enter a smaller value: ");
scanf_s("%lf", &speed);
}
double newlength = length * (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newmass = mass / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newutime = utime / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
if (speed == LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\tIt's technically impossible to reach the speed of light if you have mass but here are the mathematical limit results:\n\n\t*The new length quantity is 0\n\n\t*The new mass quantity is infinity\n\n\t*The new time quantity is infinity\n\n\n\t- Time successfully dilated -\n\n");
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
if (speed < LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\t*The new length quantity is %.20lf\n\n\t*The new mass quantity is %.20lf\n\n\t*The new time quantity is %.20lf\n\n\n\t- Time successfully dilated -\n\n", newlength, newmass, newutime);
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
}
while (answer == 'y');
return 0;
}
Thank you, have a good day
The return value of scanf is the number of elements parsed successfully; you can use this to repeat until something has been read successfully:
double nr=0;
while (!feof(stdin) && scanf("%lf",&nr)!=1) {
printf("not a number; try again.");
while ( (c = getchar()) != '\n' && c != EOF ) { }
}
Note that you have to take "invalid" input out of the buffer; otherwise, scanf would fail again and again.

if statement with char condition in C

I have been working on a college project. I want user to enter Y/N if he wants to continue or not, so I wrote following code
repeat:
pr=0;
q=0;
res=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf("%d",&res);
if(res=='y')
goto repeat;
else
return 0;
}
The problem is entering y executes else statement. I tried replacing y with 1,2,3.... and it works but I want it to work with Y or y or yes.
There is a bug in this line
scanf("%d",&res);
It should be
scanf(" %c",&res);
The formatting placeholders for char is %c not %d
scanf("%d",&res);
should be
scanf(" %c",&res);
As suggested by multiple users do while should be used over goto, so better code would be
do{
pr=0;
q=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf(" %c",&res);
}
while(*res == 'Y' || *res == 'y');
return 0;
}
Also res should also be declared char res;

How to loop a whole codeblock in C?

So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)

Resources