When I added the main while loop, the program just always runs, and runs through again and with a message telling me there is invalid data (from my first input validation). Can anyone show me how to give the user the option to end the program? Basically, I just want to give the user the option to end the program by pressing 'y or 'n'. Would be open to hearing new ideas, such as using a for, or do while loop! I just want the program to go through. I want the user to be able to go through as many times as they want, while having the option to leave after each run through.
#include <stdio.h>
//Declare functions
void displayWelcome(void);
double getAverage(double yards, double carries);
void endMessage(void);
int main()
{
//Declare variables
double yards, carries, average, bestAverage;
char again = 'y';
//Call function to display welcome message
displayWelcome();
while (again == 'y' || again =='Y') {
//Prompt user for the number of yards,
printf("Enter the number of yards:");
/*
Scan in the value of 'yards' and send user into a loop if they enter
incorrect data
While loop to validate the data of the value 'yards'
*Works with a numerical value greater than 0
*/
while ( 1 != scanf( "%lf", &yards ) || yards <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero:");
}
//Prompt user for the number of carries, followed by an input scan to get
//value of carries
printf("Enter the number of carries:");
/*
Scan in the value of 'yards' and send user into a loop if they enter
incorrect data
While loop to validate the data of the value 'carries'
*Works with a numerical value greater than zero
*/
while ( 1 != scanf("%lf", & carries) || carries <= 0)
{
//Refreshes the input value of the variable 'carries' and prompts the
//user to type in new value for 'carries'
fflush(stdin);
printf("Enter a numerical value greater than zero:");
}
average = getAverage( yards, carries);
printf("yards:%g carries:%g average:%g\n", yards, carries, average);
//Give the user the option to run the program again
printf("Would you like to run the program again? Enter (y)es or (n)o\n");
scanf("%c\n", &again);
}
endMessage();
return 0;
}
void displayWelcome(void)
{
printf("Welcome to Football Stats\n");
}
double getAverage(double yards, double carries)
{
double average;
average = yards + carries / 2;
return average;
}
void endMessage(void){
printf("\nThese results were brought to you by ");
}
UPDATE (QUESTION STILL UNANSWERED) It worked when I presses 'n' to stop the program. However, when I press 'y' to run it again (with the newly input code) it ALSO stops the program. So back to my question, can anyone see WHAT I am doing wrong so that I can give the user the option to close the program?
FINAL UPDATE I found the issue. I did "scanf("%c\n", &again);" (clearing the values) when I should have put "scanf("\n%c", &again);". Thank you to everyone who spent the time to help me!