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.
Related
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;
When I try to compile, I get only two error messages.
"Error LNK2019 unresolved external symbol "int __cdecl examAvg(void)" (?examAvg##YAHXZ) referenced in function _main
Line 1
and
LNK1120 1 unresolved externals
also on Line 1
I have worked on this so long (days) that I really can't figure out where I am going wrong anymore, I am sure it is something simple, but I am for a loss again.
Will someone please give me a suggestion to help rectify the error codes?
/*
Christopher Pierce
Date Created: July 3, 2020
Egrades Vector Application
*This application creates a C++ menu program that generates an electronic grade sheet that can keep track of five student test scores earned during the semester.
• Organizes the main program menu to call four functions.
• (1) function that allow a user to Add five students and their scores on three exams into the vector.
• (2) function that will compute the average test score for each of the five students in the vector.
• (3) function that all the user to display a student average test scores searching for their name in the vector.
• (4) function that will compute the average of the average exams in the vector and display the result.
*/
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
// Declarations
int score1;
int score2;
int score3;
int score4;
int score5;
int score6;
int score7;
int score8;
int score9;
int score10;
int score11;
int score12;
int score13;
int score14;
int score15;
string student1;
string student2;
string student3;
string student4;
string student5;
int main()
{
vector <string> StudentFile;
vector <int> Egrades;
int average1 = (score1 + score2 + score3) / 3;
int average2 = (score4 + score5 + score6) / 3;
int average3 = (score7 + score8 + score9) / 3;
int average4 = (score10 + score11 + score12) / 3;
int average5 = (score13 + score14 + score15) / 3;
// Prototype (functions)
int examAvg();
{
StudentFile.insert(StudentFile.begin(), student1);
Egrades.insert(Egrades.begin(), average1);
StudentFile.push_back(student2);
Egrades.push_back(average2);
StudentFile.push_back(student3);
Egrades.push_back(average3);
StudentFile.push_back(student4);
Egrades.push_back(average4);
StudentFile.push_back(student5);
Egrades.push_back(average5);
}
/*
Start of Menu
*/
// Defines the width of the menu
const int menuWidth = 84;
// This is a loop structure for the menu box using ASCII
// This prints the top left corner of the menu box (ASCII)
cout << char(201);
// This prints the top border of the menu box (ASCII)
for (int column = 0; column < menuWidth; ++column) {
cout << char(205);
}
// This prints the top right corner of the menu box (ASCII)
cout << char(187);
cout << "\n";
// array with menu options
string menu[15];
menu[0] = " **************";
menu[1] = " *** MAIN MENU ***";
menu[2] = " **************";
menu[3] = " Please Choose From The Following Options:";
menu[6] = " 1. Add 5 Students to Egrades Vector:";
menu[8] = " 2. Compute Student Test Score Average:";
menu[10] = " 3. Search A Student Average Test Score:";
menu[12] = " 4. Compute The Average Of All 5 Student Exam Averages:";
menu[14] = " 5. Exit";
for (string option : menu)
{
cout << char(186) // print left border
<< setw(menuWidth) // set next item width
<< left // set next item aligment
<< option // print menu option string with width and aligment
<< char(186) << "\n"; // print right border
}
// This will print the bottom left corner of the menu box (ASCII)
cout << char(200);
// This prints the bottom border of the menu box (ASCII)
for (int column = 0; column < menuWidth; ++column) {
cout << char(205);
}
// This prints the bottom right corner of the menu box (ASCII)
cout << char(188);
cout << "\n\n";
/*
END OF MENU
*/
char selection;
cout << "\t\t\t Enter Your Selection: ", cin >> selection, cout << endl;
switch (selection)
{
case '1':
system("CLS");
cout << "Student Information Section:\n\n";
// Student 1 Info, captures name and scores
cout << "\nEnter Student 1 Name: \n";
cin >> student1;
cout << "\nEnter Exam 1 Score: ";
cin >> score1;
cout << "Enter Exam 2 Score: ";
cin >> score2;
cout << "Enter Exam 3 Score: ";
cin >> score3; examAvg();
// Student 2 Info, captures name and scores
cout << "\nEnter Student 2 Name:\n";
cin >> student2;
cout << "\nEnter Exam 1 Score: ";
cin >> score4;
cout << "Enter Exam 2 Score: ";
cin >> score5;
cout << "Enter Exam 3 Score: ";
cin >> score6; examAvg();
// Student 3 Info, captures name and scores
cout << "\nEnter Student 3 Name:\n";
cin >> student3;
cout << "\nEnter Exam 1 Score: ";
cin >> score7;
cout << "Enter Exam 2 Score: ";
cin >> score8;
cout << "Enter Exam 3 Score: ";
cin >> score9; examAvg();
// Student 4 Info, captures name and scores
cout << "\nEnter Student 4 Name:\n";
cin >> student4;
cout << "\nEnter Exam 1 Score: ";
cin >> score10;
cout << "Enter Exam 2 Score: ";
cin >> score11;
cout << "Enter Exam 3 Score: ";
cin >> score12; examAvg();
// Student 5 Info, captures name and scores
cout << "\nEnter Student 5 Name:\n";
cin >> student5;
cout << "\nEnter Exam 1 Score: ";
cin >> score13;
cout << "Enter Exam 2 Score: ";
cin >> score14;
cout << "Enter Exam 3 Score: ";
cin >> score15; examAvg();
cout << "\n\n******************************************************\n";
cout << "!!! INFORMATION HAS BEEN ADDED TO EGRADES VECTOR !!!\n";
cout << "******************************************************\n\n";
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '2':
system("CLS");
for (unsigned int i = 0; i < Egrades.size(); ++i)
{
cout << Egrades[i] << endl;
}
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '3':
system("CLS");
int score;
cout << "\nEnter A Students Name To Find Their Average:\n";
cin >> score;
if (cin >> student1)
{
cout << "Average Found:\n" << average1;
}
else if (cin >> student2)
{
cout << "Average Found:\n" << average2;
}
else if (cin >> student3)
{
cout << "Average Found:\n" << average3;
}
else if (cin >> student4)
{
cout << "Average Found:\n" << average4;
}
else if (cin >> student5)
{
cout << "Average Found:\n" << average5;
}
else
{
cout << "Average not found.\n";
}
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '4':
system("CLS");
cout << "The Average of All Five Students Averages Are:\n\n";
cout << "|| " << (average1 + average2 + average3 + average4 + average5) / 5 << " ||\n\n";
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '5':
exit(-1);
break;
default: cout << "\n Invalid selection\n\n";
}
return 0;
}
I have an assignment for my intro C++ class to make a program that has a user select C, D, or E to process a check, deposit a check, or end the program respectively. The professor specified that if a user chooses C or D, he would like to accept both the selection and the amount of money in the same line. For example, if a user wants to deposit a check for $20, they would enter "D 20" in one line. I have it set up as such:
cout << "Enter the beginning balance:\n\n";
cin >> balance;
cout << "Commands:\n";
cout << "C - process a check\n";
cout << "D - process a deposit\n";
cout << "E - end the program\n\n";
while (choice != 'E')
{
cout << "Enter a transaction:\n";
cin >> choice >> amount;
Followed by a switch statement. The code itself works properly when entering C or D, but when I go to enter E to end the program, it will only work if I add a number to the end, because the line asking for input wants a char and a float. However, in the example output my professor showed, you could just enter E and it would terminate. Is there any way around this? How can I set it up so it accepts E differently from C and D?
EDIT: Here is the switch statement:
switch(choice)
{
case 'C':cout << fixed << setprecision(2);
cout << "Processing check for $" << amount << endl;
balance = processCheck(amount, balance);
cout << "Balance: $" << balance << endl;
break;
case 'D':cout << fixed << setprecision(2);
cout << "Processing deposit for $" << amount << endl;
balance = depositCheck(amount, balance);
cout << "Balance: $" << balance << endl;
break;
case 'E':cout << "Processing end of month\n";
cout << "Final balance: $" << balance << endl;
break;
default : cout << "Invalid choice\n";
}
Already answered in comments, but anyway:
Replace this code
cin >> choice >> amount;
by gradual and conditional input code:
cin >> choice;
if (choice == 'C' || choice == 'D')
cin >> amount;
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;}