I'm trying to get the following code to work. I want it to be so that if the input of the person's name is not an "x", I want it to skip the loop and end. If not, I want it to loop. I thought the condition would be something like the following:
void printProfile()
{
//make a "cookie" or OBJECT
HealthProfile user;
//get name, age, weight, height info
string personName = " ";
int yrs;
double weight, feetHeight, inchesHeight;
//while the input isn't an x, keep going. if x is inputted, skip the while loop
while(personName != "x")
{
//prompt name
cout << "Enter name or X to quit: ";
getline(cin, personName);
//prompt age
cout << "Your age: ";
cin >> yrs;
//prompt weight
cout << "Your weight: ";
cin >> weight;
//prompt height feet
cout << "Your height - feet: ";
cin >> feetHeight;
//prompt height inches
cout << "Your height - inches: ";
cin >> inchesHeight;
user.setName(personName);
user.setAge(yrs);
user.setWeight(weight);
user.setHeight(feetHeight, inchesHeight);
cout << "Health Profile for " << user.getName() << endl;
cout << fixed << setprecision(1) << "BMI: " << user.getBMI() << endl;
cout << "BMI Category: " << user.getCategory() << endl;
cout << "Max heart rate: " << user.getMaxHR() << endl;
}
}
but it actually runs the whole loop through one last time on input of "x" and then ends the program. How do I make it so that putting in x exits the program?
Change your loop condition to
while(true)
After you got the name, add a check:
if((personName == "x")
break;
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I have a kind of odd problem with my function inputData. It works fine for the first movie's input. However, when it goes to do the second movie it skips over asking you to enter in the second movie's name and goes straight to prompting you to enter in the second movie's sales. The movie's name needs to be able to include spaces.
Any ideas? Anything is greatly appreciated. Thank you
struct Movie{
string movieName;
double firstWeek;
double secondWeek;
double thirdWeek;
double fourthWeek;
double total;
double avg;
};
// prototypes
void dispMenu();
char menuChoice();
void inputData(Movie *mov);
float getValidSale();
void TotalAvgSales(Movie *mov);
void displayMovieData(Movie mov);
int main() {
cout << "Welcome to Movie Data\n";
// movie 1 and 2 structure variables
Movie movie1, movie2;
char choice = 'B';
do { // loop while not D
choice = menuChoice(); // get menu choice
switch (choice) // menu options
{
case 'A':
case 'a':
// input for first movie
cout << "First Movie\n";
inputData(&movie1);
// input for second movie
cout << endl << "Second Movie\n";
inputData(&movie2);
break;
case 'B':
case 'b':
// compute for movie 1
TotalAvgSales(&movie1);
// compute for movie 2
TotalAvgSales(&movie2);
cout << "Completed!\n";
break;
case 'C':
case 'c':
// display for first movie
cout << "First Movie\n";
displayMovieData(movie1);
// display for second movie
cout << "Second Movie\n";
displayMovieData(movie2);
case 'd':
exit;
}
} while (choice != 'D');
}
// displays the menu
void dispMenu(){
cout << "Menu Options:\n";
cout << "A) Add Data\n";
cout << "B) Compute Total and Avg\n";
cout << "C) Display Data\n";
cout << "D) Quit\n";
}
// gets menu choice and verifies that it is valid input
char menuChoice(){
char choice; // option selected
dispMenu(); // displays menu
cin >> choice;
choice = toupper(choice); // if they enter lowercase, changes it to uppercase
cin.ignore(1, '\n'); // ignores input buffer
while ( choice < 'A' || choice > 'D') // make sure it is A B C or D
{
dispMenu(); // display menu
cin >> choice;
choice = toupper(choice); // if enter lower case, make upper case
cin.ignore(1, '\n'); // ignore input buffer
}
return choice;
}
float getValidSale(){
float sale;
cout << "Please enter in the number of tickets sold...\n";
cin >> sale;
while ( sale < 0){
cout << "Please enter in the number of tickets sold (>0)...";
cin >> sale;
}
return sale;
}
here is the problem function below
void inputData(Movie *mov){
// enter movie name
cout << "Please enter in Movie name...";
getline (cin, mov->movieName);
// enter first week sales
cout << "First Week Number of Tickets Sold...\n";
cout << "Please enter the number of tickets sold...";
cin >> mov->firstWeek;
// verify input >0a
while(mov->firstWeek < 0){
cout << "Please enter in the number of tickets sold (>0)...";
cin >> mov->firstWeek;
}
// enter second week sales
cout << "Second Week Number of Tickets Sold...\n";
cout << "Please enter the number of tickets sold...";
cin >> mov->secondWeek;
// verify input >0
while(mov->secondWeek < 0){
cout << "Please enter in the number of tickets sold (>0)...";
cin >> mov->secondWeek;
}
// enter third week sales
cout << "Third Week Number of Tickets Sold...\n";
cout << "Please enter the number of tickets sold...";
cin >> mov->thirdWeek;
// verify input >0
while(mov->thirdWeek < 0){
cout << "Please enter in the number of tickets sold (>0)...";
cin >> mov->thirdWeek;
}
// enter second week sales
cout << "Fourth Week Number of Tickets Sold...\n";
cout << "Please enter the number of tickets sold...";
cin >> mov->fourthWeek;
// verify input >0
while(mov->fourthWeek < 0){
cout << "Please enter in the number of tickets sold (>0)...";
cin >> mov->fourthWeek;
}
}
// calculate the average sales
void TotalAvgSales(Movie *mov){
// adding up the sales of each week
mov -> total = mov->firstWeek + mov->secondWeek + mov->thirdWeek + mov->fourthWeek;
// finding the average
mov -> avg = mov->total/4;
}
// display the data
void displayMovieData(Movie mov)
{
cout << fixed << setprecision(2);
cout << "First Movie\n";
cout << "Division Name: " << mov.movieName << endl;
cout << "First Quarter Sales: "<< mov.firstWeek << endl;
cout << "Second Quarter Sales: "<< mov.secondWeek << endl;
cout << "Third Quarter Sales: " << mov.thirdWeek << endl;
cout << "Fourth Quarter Sales: "<< mov.fourthWeek << endl;
cout << "Total Number of Tickets Sold: " << mov.total << endl;
cout << "Average Number of Tickets Sold: " << mov. avg << endl;
}
I believe I fixed it. Right above the
getline (cin, mov->movieName);
i added a
cin.clear();
and a
cin.ignore();
This seems to work.
I have no idea how i would reject invalid inputs for the exams and assignments (valid numbers are 0.00 - 100.00). but i also need to give the user one more chance to enter a valid input. so if they put in two invalid inputs in a row for the same variable it tells the user that they need to restart the program and prevent it from running. Im new to programming so im not very good at this.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main ()
{
float exam_1;
float exam_2;
float exam_3;
float assignment_1;
float assignment_2;
float weighted_exam = .1667;
float weighted_assignment = .25;
float min_score = 0.00;
float max_score = 100.00;
string name;
cout << "Please enter student name <First Last>: "; // this will ask for the students first and last name
getline(cin, name);
cout << "\n";
cout << "\t Be sure to include the decimal point for scores.\n";
cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n";
cout << "\t For example: 80.50 \n";
cout << "\n";
cout << "Please enter your exam 1 score: ";
cin >> exam_1;
cout << "Please enter your exam 2 score: ";
cin >> exam_2;
cout << "Please enter your exam 3 score: ";
cin >> exam_3;
cout << "Please enter your assignment 1 score: ";
cin >> assignment_1;
cout << "Please enter your assignment 2 score: ";
cin >> assignment_2;
cout << endl;
cout << "-" << "OUTPUT" << "-\n";
return 0;
}
You can do like this:
do{
cout <<"\t !!! All scores should range from 0.00 to 100.00!!! \n";
cin >> exam_1;
while(exam_1 < 0.0 || exam_1>100.0);
Repeat this to all inputs
cout << "Please enter your exam 1 score: ";
cin >> exam_1;
cout << "Please enter your exam 2 score: ";
cin >> exam_2;
cout << "Please enter your exam 3 score: ";
cin >> exam_3;
To
auto ReadExamScore = [](auto& ex, char c)
{
cout << "Please enter your exam " << c << " score: ";
for (int i = 0; i < 2; i ++)
{
if (cin >> ex)
{
if (ex>= 0.0 && ex <= 100.00)
return true;
}
cout << "Please enter a valid exam score" << endl;
}
cout << "Press any key to exit..." << endl;
getchar();
exit(0);
};
ReadExamScore(exam_1,'1');
ReadExamScore(exam_2,'2');
ReadExamScore(exam_3,'3');
I have looked around and can't seem to find an answer to this. I am new to C++ and am attempting to write a program for a class that asks the user for the first and last names of 4 students and their ages. The program will then display the input names and ages and also display the average of the ages.
The issue I am having is that the program allows for input of the first name and age but then skips over the remaining three name input fields and only allows for the remaining three ages to be input.
I apologize if this ends up being a dumb question but I really am at a loss. Any help will be greatly appreciated.
Here is the code I have thus far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string studentname1;
cout << "Please enter the first student's full name:" << endl;
getline(cin, studentname1);
int age1;
cout << "Please enter the first student's age:" << endl;
cin >> age1;
string studentname2;
cout << "Please enter the second student's full name:" << endl;
getline(cin, studentname2);
int age2;
cout << "Please enter the second student's age:" << endl;
cin >> age2;
string studentname3;
cout << "Please enter the third student's full name:" << endl;
getline(cin, studentname2);
int age3;
cout << "Please enter the third student's age:" << endl;
cin >> age3;
string studentname4;
cout << "Please enter the fourth student's full name:" << endl;
getline(cin, studentname2);
int age4;
cout << "Please enter the fourth student's age:" << endl;
cin >> age4;
cout << "Hello from our group." << endl;
cout << "NAME AGE" << endl;
cout << studentname1 << " " << age1 << endl;
cout << studentname2 << " " << age2 << endl;
cout << studentname3 << " " << age3 << endl;
cout << studentname4 << " " << age4 << endl;
cout << "The average of all our ages is: " << (age1 + age2 + age3 + age4) / 4.00 << endl;
return 0;
}
Since the age variables are int, the cin >> age1; will leave the newline character in the input stream. When next you call getline(), you will get the remainder of that line - which is empty, and so on.
Also, you have a copy-paste bug in your code. getline(cint, studentname2); is run for students 2, 3 and 4.
You can either solve the problem by using getline() for all input:
string agestring;
getline(cin, agestring)
stringstream(agestring) >> age1;
or clear cin when you're done reading the age:
cin >> age1;
cin.ignore();
I am trying to implement input validation into this program but it keeps coming out wrong. I tried using another while statement but it didn't work. It normally pops up with the text which shouldn't be. I want it to show after the person inputs the wrong information. I want it so that if the data entered is invalid, they will have to re enter it.
Here is the code I have so far.
/*
1. Declare variables for month 1, 2, and 3.
2. Declare variable for Total and Average Rainfall
3. Ask user to input name of months.
4. Then ask user to input inches of rain fall.
5. Add all inches and then divide by number of inches asked. In this case, 3.
6. Display average inches of rain for all months to user.
*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string month1, month2, month3;//Declared values for months aswell as total and average rainfall.
double month1Inch, month2Inch, month3Inch;
double averageInches;
double totalInches;
char c = 'y';
do
{
cout << setprecision(2) << fixed;
cout << "Enter first month's name:";
cin >> month1;
cout << "Enter rain inches for " << month1 << ":";
cin >> month1Inch;
cout << "\n";
cout << "Enter second month's name:";
cin >> month2;
cout << "Enter rain inches for " << month2 << ":";
cin >> month2Inch;
cout << "\n";
cout << "Enter third month's name:";
cin >> month3;
cout << "Enter rain inches for " << month3 << ":";
cin >> month3Inch;
cout << "\n";
totalInches = (month1Inch + month2Inch + month3Inch);
averageInches = (totalInches) / 3;//calculating the average
//Display calculated data.
cout << "The average rainfall for " << month1 << ", " << month2 << ", " << "and " << month3 << " is " << averageInches << endl;
cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;
} while (c == 'Y'||c=='y');
if (c != 'Y' || c != 'y')
cout << "you must enter the correct choice" << endl;
system("pause");
return 0;
}
I tried putting an if statement under "cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;" but i get an infinite loops.
I am not getting any error codes. Just the text showing up with "would you like to recalculate?" line and infinite loops.
Even when I input the data with that showing, I get an infinite loop somewhere. So I deleted it.
It sounds like you want to validate the Yes or No response. That requires a loop that exits only when you have an acceptable input. It's separate from the loop that decides if the calculation should be run again.
int main() {
// ...
do {
// ...
do {
cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;
} while (c != 'Y' && c != 'y' && c != 'N' && c != 'n');
} while (c == 'Y'|| c=='y');
system("pause");
return 0;
}
I got a C++ program that waits for user input and only closes if the user inputs 'q', and will loop back to the menu if anything else is entered.
At least that's what it's supposed to do. Instead of looping back, the program closes anyway.
int main()
{
Hierarchy roster;
char input=' ';
bool done = false;
string first, last, full, boss, title;
while (done != true){
cout << "Organizational Chart builder, version 0.1" << endl;
cout << "Please choose your next command: /n";
cout << " q to quit the program " << endl;
cout << " a to add a person " << endl;
cout << " c to count the number of people under someone" << endl;
cout << " p to print the hierarchy " << endl;
cout << " r to remove someone from the hierarchy " << endl;
cin >> input;
switch(input)
{
case 'q':
done = true;
break;
case 'a':
cout << "Please enter the person't first name: ";
cin >> first;
cout << "Please enter the person's last name: ";
cin >> last;
cout << "Please enter the person's title";
cin >> title;
cout << "Please enter " + first + last +"'s boss. Please enter the full name and title. If there is none, type none:";
cin >> boss;
if (boss == "none")
roster.insert(full);
else
roster.contains(boss);
roster.insert(full);
break;
case'c':
cout << "Enter the first name of the person you are searching for: ";
cin >> first;
cout << "Enter the last name: ";
cin >> last;
cout << "What is the person's title:";
cin >> title;
full = first + " " + last + " " + title;
roster.contains(full);
roster.countb(full);
break;
case 'p':
roster.print();
break;
case 'r':
cout << "Please enter the first, last, and title of the person you want removed: ";
cin >> full;
roster.removeNode(full);
break;
}
}
cout << "Program closed. " << endl;
return 0;
}
EDIT: Got it working now. Thanks
Your return statement is in your while loop. Take it out and you should be okay.
ie. return 0;}} -> } return 0;}