C Programming Logic Error? - c

The following code compiles fine, but does not allow the user to choose whether or not the program is to run again. After giving the user the answer, the program automatically terminates. I placed the main code in a "do while" loop to have the ability to convert more than one time if I wanted too. I have tried to run the program in the command line (Mac and Ubuntu machines) and within XCode with the exact same results. Any assistance would be greatly appreciated.
C Beginner
P.S. Compiling on MacBookPro running Snow Leopard.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char anotherIteration = 'Y';
do
{
const float Centimeter = 2.54f;
float inches = 0.0f;
float result = 0.0f;
// user prompt
printf("\nEnter inches: ");
scanf("%f", &inches);
if (inches < 0) {
printf("\nTry again. Enter a positive number.\n");
break;
} else {
// calculate result
result = inches * Centimeter;
}
printf("%0.2f inches is %0.2f centimeters.\n", inches, result);
// flush input
fflush(stdin);
// user prompt
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
{
printf("\nEnter a Y or a N.");
break;
}
} while(toupper(anotherIteration == 'Y'));
printf("Program terminated.\n");
return 0;
}

You probably meant...
} while(toupper(anotherIteration) == 'Y');
since you want to convert the character, and then compare it with 'Y'.

Condition
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
is always true, so your program will terminate regardless of user input.
Moreover, you put break into virtually every if in your code intended to handle incorrect input. break will terminate the cycle and the program. This is a rather strange logic: ask user to try again and then immediately terminate the program without giving the user opportunity to actually try again. Why are you terminating the program instead of allowing the user to reenter the input?

Well,
while(toupper(anotherIteration == 'Y'));
looks like you meant to say
while(toupper(anotherIteration) == 'Y');
.. but there may be other issues.

This works.
/* convert inches to centimeters */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char anotherIteration = 'Y';
do
{
const float Centimeter = 2.54f;
float inches = 0.0f;
float result = 0.0f;
// user prompt
printf("\nEnter inches: ");
scanf("%f", &inches);
if (inches < 0)
{
printf("\nTry again. Enter a positive number.\n");
break;
}
else
// calculate result
result = inches * Centimeter;
printf("%0.2f inches is %0.2f centimeters.\n", inches, result);
// flush input
fflush(stdin);
// user prompt
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
} while(toupper(anotherIteration) != 'N');
printf("Program terminated.\n");
return 0;
}

You have two big bugs here. The first one is what you have asked for in your
question:
} while(toupper(anotherIteration == 'Y'));
anotherIteration == 'Y' will return either 1 or 0, which both equal 0 after
being passed through toupper.
What you want instead is:
} while(toupper(anotherIteration) == 'Y');
The other bug lies here:
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') || (anotherIteration != 'N'))
{
printf("\nEnter a Y or a N.");
break; // This breaks out of hte main program loop!
}
What you really want to do is ask the user again if they enter something wrong,
like this:
do
{
printf("\nWould you like to run the program again? (Y/N): ");
scanf("%c", &anotherIteration);
if ((anotherIteration != 'Y') && (anotherIteration != 'N'))
printf("\nEnter a Y or a N.");
} while ((anotherIteration != 'Y') && (anotherIteration != 'N'));

You have a few bugs, but since you're learning, you should probably figure them out. The answer to your specific question on this program is that you probably want to be using fpurge() for stdin, not fflush().

One error:
while(toupper(anotherIteration == 'Y'))
should be
while(toupper(anotherIteration) == 'Y')

Related

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.

Do while loop with Character input

I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}

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:)

input validation with float as the correct type

I have to accept an input in the rang -5 to 5. The input is suppose to be of type float. I have tried the different methods suggested on this site but they do not work.
my code
while(1)
{
while(1)
{
printf("Please enter input voltage (-5V to 5V): ");
if((scanf("%f",&e) == 1){
if(e < -5.0 || e > 5.0) /*checks to make sure input is correct*/
{
printf("Please enter another input voltage.");
continue;
}
break;
else
{
printf("please enter new input.");
continue;
}
}
d = (e+5)*(4095)/(10); /*manual calculation for digital encoding*/
printf("The conversion in decimal is: %d\n",d);
printf("The conversion in hex is: %X\n\n",d);
printf("Would you like to continue (y/n)? ");/*prompt to end program*/
scanf("%c",&userInput);
if(userInput == 'y') {continue;}
if(userInput == 'n') {break;}
}
This still causes and infinite loop if say my input is "y".
Since other methods did not work for me am I doing them wrong or is this a special case?
EDIT:
To those asking the whole program is a controlled while(1) loop because at the end another user input is taken to see if the program should end or repeat. Sorry for not mentioning this.
You probably want this:
void main()
{
float e ;
char userInput ;
while(1)
{
while(1)
{
printf("Please enter input voltage (-5V to 5V): ");
if (scanf("%f",&e) == 1)
{
if(e < -5.0 || e > 5.0) /*checks to make sure input is correct*/
{
printf("Please enter another input voltage.\n");
continue;
}
else
break ;
}
}
float d = (e+5)*(4095)/(10); /*manual calculation for digital encoding*/
printf("The conversion in decimal is: %d\n",d);
printf("The conversion in hex is: %X\n\n",d);
printf("Would you like to continue (y/n)? ");/*prompt to end program*/
scanf("\n%c", &userInput);
if(userInput == 'y') {continue;}
if(userInput == 'n') {break;}
}
}
It's not very elegant, I just modified your solution so it exits the loop as soon as you have entered a value between -5 and +5.

Yes/No Prompt in C? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm using a Yes/No user prompt to determine whether the user wants to go through the program or exit the program...when you type y or Y it will go through the program again. However, any other character, not just n or N, will discontinue the program. I was wondering how I could fix this?
int main() {
unsigned num;
char response;
do {
printf("Please enter a positive integer greater than 1 and less than 2000: ");
scanf("%d", & num);
if(num > 1 && num < 2000) {
printf("All the prime factors of %d are given below: \n", num);
printPrimeFactors(num);
printf("\n\nThe distinct prime factors of %d are given below: \n", num);
printDistinctPrimeFactors(num);
} else {
printf("Sorry that number does not fall within the given range.\n");
}
printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
getchar();
response = getchar();
}
while (response == 'Y' || response == 'y'); // if response is Y or y then program runs again
printf("Thank you for using my program. Good Bye!\n\n"); //if not Y or y, program terminates
return 0;
}
I hope you are expecting the below logic to get only y, Y, n or N as input from use to take a decision.
do
{
...
r = getchar();
if (r == '\n') r = getchar();
while(r != 'n' && r != 'N' && r != 'y` && r != `Y`)
{
printf("\invalid input, enter the choice(y/Y/n/N) again : ");
r = getchar();
if (r == '\n') r = getchar();
}
}while(r == 'Y' || r == 'y');
any other character, not just n or N, will discontinue the program. I
was wondering how I could fix this
In that case you probably want to test:
while(tolower(response) != 'n'));
I can only presume the empty getchar() is there to throw away the newline. There are better ways to do this but in this case you could simply add a space to the scanf:
scanf("%d ", &num);
^
I think the problem is since you are using two getchar() in your program. .
We dont know the error. still you can try removing the getchar() immediately after the printf in your program.
Additionally... you may want to replace
getchar();
response = getchar();
with:
char c;
do{
printf("Do you want to continue? (y/n)");
scanf(" %c",&c); c = toUpper(c);
}while(c != 'N');
Note that (though not necessary), the space ahead of %c is to eliminate white spaces
Substitute the line that reads getchar(); with fflush(stdin);
Working well for me, this is the complete code.
#include <stdio.h>
#include <string.h>
int main(){
unsigned num;
char response;
do {
printf("Please enter a positive integer greater than 1 and less than 2000: ");
scanf("%d", &num);
if (num > 1 && num < 2000){
printf("All the prime factors of %d are given below: \n", num);
printPrimeFactors(num);
printf("\n\nThe distinct prime factors of %d are given below: \n", num);
printDistinctPrimeFactors(num);
}
else{
printf("Sorry that number does not fall within the given range.\n");
}
fflush(stdin);
printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
response = getchar();
} while(response == 'Y' || response == 'y');
printf("Thank you for using my program. Good Bye!\n\n");
return 0;
}

Resources