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.
Related
I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
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;
}
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:)
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;
}
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')