My code asks me to convert:
2 6 2 // # of quizzes (2), homeworks(6), exams(2)
Solution Key 10 10 10 10 20 20 20 20 100 100
Washington George 10 10 10 10 20 20 20 20 100 100
Jefferson Thomas 10 0 8 6 20 15 13 0 80 90
Franklin Benjamin 0 0 0 0 20 10 20 10 100 50
Lincoln Abraham 10 5 10 5 0 0 0 0 80 30
Madisonville James 5 7 9 3 10 12 14 16 0 0
Wilson Woodrow 2 4 6 8 10 12 14 16 74 89
Hoover Herbert 0 10 10 10 0 20 20 20 0 100
Roosevelt Franklin 0 0 0 0 0 0 0 0 0 0
Into this (in an output file):
# Last First Quiz HW Exam Total Average
- ---------- ----- ---- --- ---- ----- -------
Solution Key 20 100 200 320 100.00
- ---------- ----- ---- --- ---- ----- -------
1 Washington Georg 20 100 200 320 100.00
2 Jefferson Thoma 10 62 170 242 75.62
3 Franklin Benja 0 60 150 210 65.62
4 Lincoln Abrah 15 15 110 140 43.75
5 Madisonvil James 12 64 0 76 23.75
6 Wilson Woodr 6 66 163 235 73.44
7 Hoover Herbe 10 80 100 190 59.38
8 Roosevelt Frank 0 0 0 0 0.00
- ---------- ----- ---- --- ---- ----- -------
Class Average = 55.20
I have been using count controlled loops to obtain the quiz, homeworks, and exam scores, however my output looks like this:
# Last First Quiz HW Exam Total Average
- ---------- ----- ---- --- ---- ----- -------
- ---------- ----- ---- --- ---- ----- -------
- ---------- ----- ---- --- ---- ----- -------
Class Average = 1458176112
Here is my code:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <typeinfo>
using namespace std;
//Sample solution
//- /home/work/cpe211/Executables/Project_06/Project_06_solution
//Comparison script
//- /home/work/cpe211data/Project_06/CompareSolution.bash Project_06.cpp
int main(int argc, char* argv[])
{
if (argc != 3) // if the amount of arguments is greater than 2, perform this.
{
cout << endl;
cout << "Incorrect number of command line arguments provided. \n";
cout << "This program requires 2 command line arguments: \n";
cout << "An input filename and an output filename \n \n";
cout << "Program usage is: \n";
cout << "./Project_06 InputFileName OutputFileName \n \n";
return 1;
}
// Variable Delcaration
ifstream inFile; // input
ofstream outFile; // output
string inputFileName, outFileName;
string line1, line2, line3, first, last;
int quiznum, homenum, examnum, quiz, homework, exam, total, average, total_sol, count_quiz, count_exam, count_homework, count, homework_total, exam_total, quiz_total, average_p2, average_total;
// ***** Opening and naming command line argument ***** //
inputFileName = argv[1]; // assign command line argument value to a string variable
inFile.open(inputFileName.c_str());
cout << "Opening Input File: " << inputFileName << endl;
outFile.open(argv[2]);
cout << "Opening Output File: " << argv[2] << endl;
// ***** Testing to see if the file exists ***** //
while (inFile.fail()) // if the file does not exist, then do this.
{
cout << endl;
cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
cout << "==> Input file failed to open properly!!\n";
cout << "==> Attempted to open file: " << inputFileName << endl;
cout << "==> Please try again...\n";
cout << string(47,'*') << endl << endl;
inFile.clear(); // clears the input file stream
cout << "Enter the name of the input file: ";
cin >> inputFileName; // user inputs new name of file
inFile.open(inputFileName.c_str()); // opens the new input file
cout << inputFileName << endl; // echo prints the new input file name
cout << "Opening Output File: " << argv[2] << endl; // echo the output fule
}
// ***** Testing for output file existance ***** //
while (outFile.fail()) // if the file does not exist, then do this.
{
cout << endl;
cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
cout << "==> Output file failed to open properly!!\n";
cout << "==> Attempted to open file: " << argv[2] << endl;
cout << "==> Please try again...\n";
cout << string(47,'*') << endl << endl;
outFile.clear();
cout << "Enter the name of the output file: ";
cin >> outFileName; // recieves input for the new output file name
outFile.open(outFileName.c_str()); // opens the output file
cout << outFileName << endl; // echo prints new output file name
}
// ***** First line information ***** //
getline(inFile,line1,'\n'); // gets line 1
inFile >> quiz >> homework >> exam; // retrieves number of quiz, homework, and exam scores from the first line.
if (inFile.eof())
{
cout << endl;
cout << "*************" << " Input File Is Empty " << "*************" << endl;
cout << "==> The input file is empty.\n";
cout << "==> Terminating the program.\n";
cout << string(47,'*') << endl << endl;
outFile << "Input file " << inputFileName << " is empty. \n";
return 1;
}
// ***** Count initializers ****** //
count = 0;
count_quiz = 0;
count_homework = 0;
count_exam = 0;
// ***** Starting for output ***** //
outFile << " # " << "Last " << "First " << "Quiz " << " HW " << "Exam " << "Total " << "Average" << endl; // First line info for each part of the file
outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl; // seperating dashes
// ***** Sample solution data ***** //
getline(inFile,line2,'\n');
while (inFile >> last >> first)
{
while (count_quiz < quiz)
{
inFile >> quiz; // gets the quiz scores
quiz_total = quiz + quiz; // total of all quiz scores
count_quiz++;
}
while (count_homework < homework)
{
inFile >> homework;
homework_total = homework + homework;
count_homework++;
}
while (count_exam < exam)
{
inFile >> exam; // gets exam scores
exam_total = exam + exam; // totals all exam scores found
count_exam++; // updates count
}
total_sol = quiz_total + homework_total + exam_total; // total score for solution set
average = (total_sol / total_sol) * 100; // average for solution set (100%)
outFile << last << first << quiz_total << homework_total << exam_total << total_sol << average << endl; // output of all the above info
}
outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl; // seperating dashes
// ********* The following grabs the info from each line using count controlled loops ********* //
getline(inFile,line3,'\n'); // gets the new lines
while (inFile >> last >> first)
{
while (count_quiz < quiz) // while the count is less than the number of the quizzes, do this.
{
getline(inFile,line3,'\n'); // gets line 3 and updates each time
inFile >> quiz; // quiz scores
quiz_total = quiz + quiz; // total of all the quiz scores
outFile << quiz_total; // output for total quiz scores
count_quiz++; // updates count
}
while (count_homework < homework) // while the count is less than the number of specified homeworks, do this
{
getline(inFile,line3,'\n'); // gets line 3 and updates each time
inFile >> homework; // homework scores
homework_total = homework + homework; // total of all homework scores
outFile << homework_total; // output for total homework scores
count_homework++; // updates count
}
while (count_exam < exam) // while the count is less than than the number of specified exams, do this.
{
getline(inFile,line3,'\n'); // gets line 3 and updates each time
inFile >> exam; // exam scores
exam_total = exam + exam; // total of all exam scores
outFile << exam_total; // output for total exam scores
count_exam++; // updates count
}
outFile << last << first << quiz_total << homework_total << exam_total << endl;
total = quiz_total + homework_total + exam_total; // total # of quiz, homeworks, and exam scores added
average_p2 = total / average; // average for each student
average_total = (average_p2 + average_p2) / count; // total average for all students
}
outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl << endl; // seperating dashes
outFile << "Class Average = " << average_total << endl; // outputs the total average of the exam.
outFile.close();
return 0;
}
TLDR: How do I loop through a text file and get its info, use them in calculations, and output it correctly?
Related
This is the file_processing_tutor.cpp file:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include "ClientData.h"
using namespace std;
void outputline(int, const string &, double);
void outputlineDAT(ostream&, const ClientData &);
int main() {
cout << endl << "Phase 1 Writing Data to txt" << endl;
cout << "Make Sure Input is already ready before running" << endl;
ofstream outClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::out);
if(!outClientFile){
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
cout << "Enter the account, name, and balance" << endl << "Enter end-of-file to end input." << endl;
int count_input = 0;
int account;
string name;
double balance;
while(cin >> account >> name >> balance){
++count_input;
outClientFile << account << ' ' << name << ' ' << balance << endl;
cout << "? (Input Count = " << count_input << ") " << endl;
}
cout << endl << endl << "Phase 2 Reading Data from txt" << endl;
ifstream inClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::in);
if(!inClientFile){
cerr << "File Could not be Opened" << endl;
exit(EXIT_FAILURE);
}
cout << left << setw(10) << "Account" << setw(13) << "Name" << "Balance" << endl << fixed << showpoint;
while(inClientFile >> account >> name >> balance){
outputline(account, name, balance);
}
cout << endl << "Phase 3 Writing 100 Blank Records to Random Access File .Dat" << endl;
fstream outCredit("C:/Users/User/Desktop/Streaming DT Data/credit.dat", ios::out | ios::in | ios::binary);
if(!outCredit){
cerr << "File Could not be opened" << endl;
exit(EXIT_FAILURE);
}
ClientData blankClient;
for(int i = 0; i < 100; ++i){
outCredit.write(reinterpret_cast <const char *>(&blankClient), sizeof(ClientData));
}
cout << endl << "Phase 4 Writing Data Randomly to a Random Access File .Dat" << endl;
string firstName;
string lastName;
cout << "Enter Account Number (1 to 100, 0 to end input)\n?";
ClientData client;
cin >> account;
cout << "Account Input: " << account << endl;
while(account > 0 && account <= 100){
cout << "Enter lastname, firstname, balance \n?";
cin >> lastName >> firstName >> balance;
client.setAccountNumber(account);
client.setLastName(lastName);
client.setFirstName(firstName);
client.setBalance(balance);
outCredit.seekp((client.getAccountNumber() - 1) * sizeof(ClientData));
cout << "Enter Account Number (1 to 100, 0 to end input)\n?";
cin >> account;
}
return 0;
}
void outputline(int account, const string &name, double balance){
cout << left << setw(10) << account << setw(13) << name << setw(7)
<< setprecision(2) << right << balance << endl;
}
void outputlineDAT(ostream &output, const ClientData &record){
output << left << setw(10) << record.getAccountNumber() << setw(16)
<< record.getLastName() << setw(11) << record.getFirstName() << setw(10)
<< setprecision(2) << right << fixed << showpoint << record.getBalance() << endl;
}
Because I am using Sublime Text 3, I set my input in a file called inputf.in, this is all my raw input:
100 Jones 24.98
200 Doe 345.67
300 White 0
400 Stone -42.16
500 Rich 224.62
450 Harmond 412.5
3
Barker Doug 0
29
Brown Nancy -24.54
96
Stone Sam 34.98
88
Smith Dave 258.34
33
Dunn Stacey 314.33
0
And I see my output as follows from outputf.out:
Phase 1 Writing Data to txt
Make Sure Input is already ready before running
Enter the account, name, and balance
Enter end-of-file to end input.
? (Input Count = 1)
? (Input Count = 2)
? (Input Count = 3)
? (Input Count = 4)
? (Input Count = 5)
? (Input Count = 6)
Phase 2 Reading Data from txt
Account Name Balance
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
450 Harmond 412.50
Phase 3 Writing 100 Blank Records to Random Access File .Dat
Phase 4 Writing Data Randomly to a Random Access File .Dat
Enter Account Number (1 to 100, 0 to end input)
?Account Input: 450
Problem:
So every output in above was ok, until it reached phase 4 where I get to input new data for account variable, Instead of get the input 3 (which is set from the input) it reoutputs the last account data (450) ignoring the cin input. thus it didn't input anything to a file called credit.dat.
Appreciate any pointers to the issues, Thankyou!
The program doesn't print the report in columns formatted exactly as shown in the sample output. Can anyone help?
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
char user_gender, user_smoker;
string user_eyecolor;
int user_minAge, user_maxAge, user_minHeight, user_maxHeight;
cout << "What is the gender of your ideal match(M, F, N) ? ";
cin >> user_gender;
cout << "What is the minimum age? ";
cin >> user_minAge;
cout << "What is the maximum age? ";
cin >> user_maxAge;
cout << "What is the minimum height (in inches)? ";
cin >> user_minHeight;
cout << "What is the maximum height (in inches)? ";
cin >> user_maxHeight;
cout << "Smoker (Y/N)? ";
cin >> user_smoker;
cout << "What is the eyecolor (Blue, Green, Grey, Brown)? ";
cin >> user_eyecolor;
cout << endl << endl;
//Variables to check against the conditions
int countGender = 0;
int partialMatch = 0;
int fullMatch = 0;
cout << endl << left << setw(1) << " Name" << fixed << right << setw(22) << "Age" << fixed << right << setw(12) << "Height" << fixed << right << setw(12) << "Smoker" << fixed << right << setw(15) << "Eye Color" << fixed << right << setw(22) << "Phone" << endl;
cout << "-----------------------------------------------------------------------------------------------------------------" << endl;
//Now read the file data.
ifstream fin("matches.txt");
if (fin.is_open())
{
while (!fin.eof())
{
string firstname, lastname, eyecolor, phoneno;
char gender, smoker;
int age, height;
fin >> firstname >> lastname >> gender >> age >> height >> smoker >> eyecolor >> phoneno;
if (gender == user_gender)
{
countGender++;
//Now check to see if the age and height are between the maximum and minum preferences.
if ((age >= user_minAge && age <= user_maxAge) && (height >= user_minHeight && height <= user_maxHeight))
{
//Then check to see if the smoking preference and eye color are also a match.
if (user_smoker == smoker && user_eyecolor == eyecolor)
{
fullMatch++;
cout << "* " << firstname << " " << lastname << setw(25) << age << setw(11) << height << setw(11) << smoker << setw(11) << eyecolor << setw(11) << phoneno << endl;
}
else if (eyecolor == user_eyecolor)
{
partialMatch++;
cout << " " << firstname << " " << lastname << setw(24) << age << setw(11) << height << setw(11) << smoker << setw(11) << eyecolor<< setw(11) << phoneno << endl;
}
}
}
}
cout << "-----------------------------------------------------------------------------" << endl;
cout << "There were " << fullMatch << " matches and " << partialMatch << " partial matches out of " << countGender << " records." << endl;
cout << "-----------------------------------------------------------------------------" << endl;
fin.close();
}
else {
cout << "File did not open";
}
return 0;
}
****The program is working perfectly fine, but I am not getting the output printed in columns formatted as shown in the above sample output. ****
Write a program that opens the file and reads the records one by one. The program will skip any records where the gender preference is not a match. Of those records that match the gender preference, check to see if the age and height are between the maximum and minimum preferences. Then check to see if the smoking preference and eye color are also a match. If at least 3 of the remaining fields match, consider the record a partial match, and print it in the report. If all 4 of the remaining fields match, the record is a perfect match and print it in the report with an asterisk next to it. At the end of the program, close the file and report how many total records there were of the specified gender, how many were a partial match, and how many were a perfect match.
Charlie Bradbury F 42 65 N Green 555-867-5309
Bobby Singer M 70 69 Y Brown 555-867-5309
Dean Winchester M 43 72 N Brown 555-867-5309
Sam Winchester M 39 75 N Brown 555-867-5309
Bela Talbot F 39 69 Y Blue 555-867-5309
James Novak M 46 71 Y Blue 555-867-5309
Use a proper IDE with debugging capabilities (e.g. Visual Studio Community Edition).
Set a breakpoint at the first line of the method which is problematic, e.g. line 9 in your case
Step over your code line by line and see what it does.
Hover over variables or use the locals or watch window to see the values of variables
Think about what you expected to see and compare it to what you actually see. In 99% of the cases, the computer is more right than you and it's a misunderstanding on your side.
I want my program to be aligned correctly; I'm using the iomanip (setw) library but I'm still getting the wrong output:
The output I want is:
1001 Butter 9.45 50 100 74
1002 Milk-1L 12.85 100 150 83
1003 Flour-Bak 13.45 210 500 410
The output I'm getting currently is:
1001 Butter 9.45 50 100 74
1002 Milk-1L 12.85 100 150 83
1003 Flour-Bak 13.45 210 500 410
Here is my code:
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
// Function Declaration
void displaymenu();
void Inventory();
void empgrossnet();
void employavgdeduc();
// Size of Array
const int SIZE = 10;
int i;
// Initialize Struct function for Employee Data
struct InventoryData {
int Itemnum;
string Name;
double UnitPrice;
int Minimumlevel;
int Optimumlevel;
int Qtyinstock;
} InventoryItems[SIZE];
// Initialize/Read file into the program
ifstream thefile("i_Data.txt");
int main() {
while (true) {
displaymenu();
}
return 0;
}
void displaymenu() {
int option;
// print menu options and prompt user to enter a menu option
printf("\n***************** Employee Data *******************\n");
printf("[1] Press 1 for Inventory Data Records\n");
printf("[2] Press 2 for Employee Gross and Net Pay\n");
printf("[3] Press 3 for Average Hours and Average Deductions\n");
printf("[4] Exit Program\n");
printf("\n****************************************************\n");
printf("\n Enter an option>>\t");
scanf("%d", &option);
switch (option) {
case 1:
Inventory();
break;
case 4:
printf("\n\n Thank you for using the Program");
printf("\n Exiting Application....");
exit(0);
}
}
void Inventory() {
// Read from edata.txt File
ifstream thefile("i_Data.txt");
// Check to make sure that Program is finding/reading from edata file
if (!thefile) {
cerr << "File can't be opened! " << endl;
system("PAUSE");
exit(1);
}
// Creat loop to store 5 lines of information from edata file
for (int i = 0; i < SIZE; i++) {
thefile >> InventoryItems[i].Itemnum >> InventoryItems[i].Name >>
InventoryItems[i].UnitPrice
>> InventoryItems[i].Minimumlevel >> InventoryItems[i].Optimumlevel >>
InventoryItems[i].Qtyinstock;
}
// Output/Display Edata file information into prgram
printf("\n************************************* EMPLOYEE DATA "
"****************************************\n");
printf("\n %s %15s %20s %15s %15s ", "EmployeeID", "Employee Name",
"Hours Worked", "Rate of Pay", "Deductions");
printf("\n-------------------------------------------------------------------"
"------------------\n");
for (int i = 0; i < SIZE; i++) {
cout << setw(10) << " " << InventoryItems[i].Itemnum;
cout << setw(10) << " " << InventoryItems[i].Name;
cout << setw(10) << " " << InventoryItems[i].UnitPrice;
cout << setw(10) << " " << InventoryItems[i].Minimumlevel;
cout << setw(10) << " " << InventoryItems[i].Optimumlevel;
cout << setw(10) << " " << InventoryItems[i].Qtyinstock << endl;
}
printf("\n-------------------------------------------------------------------"
"------------------\n");
}
You seem to want
cout <<" " << setw(10) << InventoryItems[i].Itemnum;
cout <<" " << setw(10) << InventoryItems[i].Name;
cout <<" " << setw(10) << InventoryItems[i].UnitPrice;
cout <<" " << setw(10) << InventoryItems[i].Minimumlevel;
cout <<" " << setw(10) << InventoryItems[i].Optimumlevel;
cout <<" " << setw(10) << InventoryItems[i].Qtyinstock<<endl;
Your original code outputs 10 spaces then values. I believe you want single spaces and values in 10-char placeholders.
Input file that has the name, some number, another number, then an identification number, followed by a cost:
Jennifer Jones
145634
2
EX1 50.00
BD1 25.00
Paul Peters
173409
4
EX2 75.00
BD2 120.00
XR1 250.00
EQ1 50.00
The code I have so far:
//Input the patient's name from the input file
getline(fin, patientName);
//while there is data in the input file
while (fin)
{
//Initial Processing for a Patient---------------------------------------------------------
//Input the patient's id & the number of services from the input file
fin >> patientIdentificationNumber >> numberOfServices;
//Output the divider to the output file
fout << setfill('*') << setw(SCREEN_WIDTH + 1) << ' ' << setfill(' ') << endl;
//Output the patient's name, patient's id number & the number of services to the output file
fout << "Patient Name: " << patientName << endl
<< "Patient's ID Number: " << patientIdentificationNumber << endl
<< "Number Of Services: " << numberOfServices << endl;
//Output the divider to the output file
fout << setfill('*') << setw(SCREEN_WIDTH + 1) << ' ' << setfill(' ') << endl;
//Output a blank line to the output file
fout << endl;
//Output the heading for the service id & cost to the output file
fout << left << setw(20) << "Service ID"
<< right << setw(20) << "Cost" << endl;
//Output the divider to the output file
fout << setfill('*') << setw(SCREEN_WIDTH + 1) << ' ' << setfill(' ') << endl;
//
//Initialize the patient's total bill
patientTotalBill = 0;
//Patient Processing-----------------------------------------------------------------------
//for
for()
{
//Input
//
//
//Output the service id & the cost of the service to the output file
fout << left << setw(20) << serviceIdentifcation
<< right << setw(20) << serviceCost << endl;
//end for
}
How do I make the for loop work? It has to be in this setup with the while loop and for loop inside of it.
Just read numberOfServices times:
for (int i = 0; i < numberOfServices; ++i) {
fin >> serviceName >> serviceCost;
// do whatever you want with the info.
}
This code is used to run a loop three times, that takes the numbers of eggs gathered and outputs the number in dozens and extra until the user enters a negative number. Then, it prints out the average amount of eggs gathered (entered), and outputs the total number of dozens and extra.
The inputs we were assigned to use are:
43,
31,
-1,
24,
8,
14,
-999,
-5.
Everything is fine up until we input -5. Our teacher doesn't want the average or total number of dozens and extras to print (you'll see what I mean in the output).
The source code is as follows:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int eggNum;
int eggDozens;
int eggExtra;
int eggTotal;
int loopCount;
int forCount;
float eggAvg;
int totalDozens;
int totalExtra;
for(forCount = 1; forCount <= 3; forCount=forCount + 1)
{
cout << left << "TEST #" << forCount << ":" << endl;
cout << "Welcome to Aunt Ellen\'s eggs to dozens converter!";
cout << endl << endl;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
eggTotal = 0;
loopCount = 0;
while(eggNum >= 0)
{
eggDozens = eggNum / 12;
eggExtra = eggNum % 12;
if(eggDozens != 0)
{
if(eggExtra != 0)
{
cout << "\tYou have " << eggDozens << " dozen ";
cout << eggExtra << " eggs.";
cout << endl << endl;
}
else
{
cout << "\tYou have " << eggDozens << " dozen eggs.";
cout << endl << endl;
}
}
else
{
cout << "\tYou have " << eggExtra << " eggs.";
cout << endl << endl;
}
loopCount = loopCount + 1;
eggTotal = eggTotal + eggNum;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
}
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal / 12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
return 0;
}
And the output:
TEST #1:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 43
You have 3 dozen 7 eggs.
Enter the number of eggs gathered: 31
You have 2 dozen 7 eggs.
Enter the number of eggs gathered: -1
TOTALS:
On average 37 eggs have been gathered.
A total of 6 dozen 2 and eggs have been gathered!
TEST #2:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 24
You have 2 dozen eggs.
Enter the number of eggs gathered: 8
You have 8 eggs.
Enter the number of eggs gathered: 14
You have 1 dozen 2 eggs.
Enter the number of eggs gathered: -999
TOTALS:
On average 15.3333 eggs have been gathered.
A total of 3 dozen 10 and eggs have been gathered!
TEST #3:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: -5
TOTALS:
On average -1.#IND eggs have been gathered.
A total of 0 dozen 0 and eggs have been gathered!
I don't want the very last "TOTALS" and the lines following. I want the program to terminate after entering -5.
The simplest thing is to do this before entering the while loop:
cin >> eggNum;
if (eggNum < 0)
break ;
That will quit the for loop, and return 0;
You may, if you want to, add some comments to the caller about entering negative numbers before calling break.
You mentioned that you only want to omit the last block of TOTALS.
You can simply add a special case to leave the outer loop early in this case.
Right before this block, but after the closing brace of the while loop.
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
Insert this:
if (forCount == 3) break;
If you just want to avoid printing whenever the average is less than 0, then instead you should insert in the same location.
if (eggAvg < 0) continue;
This will skip the rest of that iteration of the for loop.
I think a simple answer to your problem would be to just put an if statement around the printing total code. Like this:
if(eggNum > -5){ //won't print for negative 5
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal / 12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
I hope this helps!