Hi my assignment is due in a couple of hours and I am trying to write my code to produce this output but it is not working. My program doesn't even run at all and always fails and I don't know what the issue is. I'm having issues with what to place in int main() and how to process the data from file to the functions! I have been trying forever.. In need of major help !!!!! thanks for your time
sample input file :
Miss Informed
125432 32560.0
Sweet Tooth
5432 9500
Bad Data
1255 -4500.0
John Smith
1225 3500.0
Nancy Brown
1555 154500.0
CODE:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
float CalcIncomeTax(float );
float CalcNetSalary(float, float );
bool OpenFile(ifstream& fin);
bool OpenFile(ofstream& fout);
void Instruct(void);
void ReadData(ifstream & fin, string& Name , int &Id, float& grossIncome);
void Print(ofstream&, string, int, float, float, float);
ifstream fin;
ofstream fout;
string Name;
int Id = 0;
float grossIncome = 0;
float netSalary;
float incomeTax = 0;
Instruct ();
netSalary = CalcNetSalary(grossIncome,incomeTax);
incomeTax = CalcIncomeTax(grossIncome);
Print(fout, Name, Id, grossIncome, incomeTax, netSalary);
ReadData(fin, Name, Id, grossIncome);
OpenFile(fin);
{
getline(fin, Name);
while (!fin.eof())
{
fin >> Id >> grossIncome;
cout << setw(20) << left << Name
<< setw(8) << right << Id
<< setw(10) << grossIncome << endl;
fin.ignore(10,'\n');
fin >> Id >> grossIncome;
}
getline(fin,Name);
}
OpenFile(fout);
ReadData(fin, Name, Id, grossIncome);
fin.close();
}
bool OpenFile(ifstream&fin)
{
cout <<"\nEnter the name and location of the input file: ";
string file_input;
getline(cin, file_input);
fin.open(file_input.c_str() ) ;
if(fin.fail())
return false;
else
return true;
}
bool OpenFile(ofstream &fout)
{
cout <<"Enter the name and location of the output file: ";
string file_output;
getline(cin, file_output);
fout.open( file_output.c_str() );
if (fout.fail())
return false;
else
return true;
}
void Instruct()
{
cout << "Programmer:"<< setw(25) << "//" << endl;
cout << "Programming Assignment" << setw(5) << "4" << endl;
cout << "This program will calculate and report tax liability" << endl;
}
float CalcIncomeTax(float grossIncome)
{
float incomeTax = 0;
if (grossIncome <= 3500)
{
incomeTax = 0.00;
}
else if (grossIncome >= 3500 && grossIncome <= 8000)
{
incomeTax = 0 + 0.06 * (grossIncome - 3500);
}
else if (grossIncome >= 8000 && grossIncome <= 20000)
{
incomeTax = 270.00 + 0.11 * (grossIncome - 8000);
}
else if (grossIncome >= 20000 && grossIncome <= 34000)
{
incomeTax = 1590.00 + 0.17 * (grossIncome - 20000);
}
else if (grossIncome >= 34000 && grossIncome <= 54000)
{
incomeTax = 3970.00 + 0.24 * ( grossIncome - 34000);
}
else if (grossIncome >= 54000)
{
incomeTax = 8770.00 + 0.32 * ( grossIncome - 52000);
}
else if (grossIncome < 0)
{
cout << "****Invalid Income";
}
return(incomeTax);
}
float CalcNetSalary( float grossIncome, float incomeTax)
{
float netSalary;
netSalary = grossIncome - incomeTax;
return (netSalary);
}
void Print(ofstream& fout, string Name, int Id, float grossIncome, float incomeTax, float netSalary)
{
cout << setfill(' ') << left << setw(18) << "\tName";
cout << setfill(' ') << left << setw(12) << "ID";
cout << setfill(' ') << left << setw(17) << "Gross Income";
cout << setfill(' ') << left << setw(12) << "Taxes";
cout << setfill(' ') << left << setw(16) << "Net Income";
cout << endl;
cout << setfill('=') << setw(70)<<"\t";
cout<<endl;
cout << setprecision(2) << showpoint << fixed;
cout << setfill(' ') << "\t" << setw(17)<< Name;
cout << setfill(' ') << setw(12) << Id;
cout << '$' << setfill(' ') << setw(16) << grossIncome;
cout << '$' << setfill(' ') << setw(11) << incomeTax;
cout << '$' << setfill(' ') << setw(16) << netSalary;
cout << endl;
}
HOW OUTPUT SHOULD BE
Name ID Gross Income Taxes Net Income
Miss Informed 125432 $32560.00 **** Invalid ID
Sweet Tooth 5432 $9500.00 $435.00 $9065.00
Bad Data 1255 $-4500.00 **** Invalid Income
John Smith 1225 $3500.00 $0.00 $3500.00
Nancy Brown 1555 $154500.00 $40930.00 $113570.00
The way to write a program is not to write everything and then try to run it. Start small and simple, add complexity a little at a time, test at every step and never add to code that doesn't work.
This will take a few iterations. We'll start with something that can read from a file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // This is a good TEMPORARY SHORTCUT.
int main()
{
ifstream fin("inputdata");
string firstName, lastName;
fin >> firstName >> lastName;
cout << "First name is " << firstName << endl;
cout << "Last name is " << lastName << endl;
return(0);
}
Post a comment when you have this working, and we'll go the next step.
Related
New to C++. I have a homework program I am programming. It is all but done, but our teacher wants us to add error catching to the program.
The issue arises in the code for asking the user to run again. I use a while loop to monitor a variable until it changes.
This works:
#include <iostream>
using namespace std;
int main() {
char runAgainYN;
while ( toupper(runAgainYN != 'N' ) {
// Do some stuff here!
cout << "Would you like to run again?";
cin >> runAgainYN;
}
return 0;
}
It keeps looping the program until runAgain is equal to 'N', then stops. Now, I modified the program to utilize some error correction for the question about running the program again, to limit the user to only entering Y or N. Here is the updated code:
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char runAgainYN;
bool runAgain = true;
while ( runAgain ) {
// Do some stuff here!
bool validResponse = false;
while ( !validResponse ) {
cout << "Would you like to run the program again (Y/N): ";
cin >> runAgainYN;
if ( toupper(runAgainYN) == 'Y' ) {
validResponse = true;
cin.ignore();
}
else if ( toupper(runAgainYN) == 'N' ) {
runAgain = false;
validResponse = true;
cin.ignore();
}
else {
cout << "INVALID RESPONSE" << endl;
}
}
}
return 0;
}
Here is where the problem arises. If the user enters 'N', the program exits with code 0, and if the user enters anything but Y or N, the invalid response triggers and asks for the input again. But, if the user enters Y, the program exits with code -1. Huh? I tried a different approach, with the same result:
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char runAgainYN;
do {
// Do some stuff here!
bool validResponse = false;
while ( !validResponse ) {
cout << "Would you like to run the program again (Y/N): ";
cin >> runAgainYN;
if ( toupper(runAgainYN) == 'Y' ) {
validResponse = true;
cin.ignore();
}
else if ( toupper(runAgainYN) == 'N' ) {
runAgain = false;
validResponse = true;
cin.ignore();
}
else {
cout << "INVALID RESPONSE" << endl;
}
}
}
while ( runAgain );
return 0;
}
Any help guys? Thanks!!!
OK, so it seems to be something in the actual program causing it. Here's the source code:
#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include <cctype>
#include <limits>
#include <algorithm>
#include <fstream>
using namespace std;
void cls();
void printLine( int length );
void showCurrency( double dv, int width = 14 );
int main() {
string itemName[999][2];
double itemPrice[999][3];
double salesTotal = 0.0;
double salesTax = 0.0;
double totalTax = 0.0;
double taxRate = 0.0;
double grandTotal = 0.0;
double test = 0.0;
int numLines = 0;
string readLine;
string temp;
ifstream fileIn;
string menuHeader = "Sales Receipt from File";
char runAgainYN;
bool runAgain = true;
do { // Loop until runAgain false
// Open the file and count the number of lines, then close for next operation:
fileIn.open("cost.txt");
while (!fileIn.eof()) {
fileIn >> temp;
numLines++;
temp = "";
}
fileIn.close();
// Open the file and move the data into the arrays, then close:
fileIn.open("cost.txt");
for ( int i = 0; i < numLines; i++) {
fileIn >> itemName[i][1] >> itemPrice[i][1];
}
fileIn.close();
cls();
numLines = numLines / 2;
cout << "/";
printLine(80);
cout << "\\" << endl;
cout << "|" << setw(81) << "|" << endl;
cout << "|" << setw(41 + (menuHeader.length() / 2)) << menuHeader << setw(40 - (menuHeader.length() / 2)) << "|" << endl;
cout << "|" << setw(81) << "|" << endl;
cout << "\\";
printLine(80);
cout << "/" << endl << endl;
cout << "Enter the sales tax percentage (ie for 6% enter 6): ";
// Ask for taxRate and error check:
while (!(cin >> taxRate)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "INVALID RESPONSE" << endl << "Please enter a number: ";
}
cout << endl;
salesTax = taxRate / 100; // Convert sales tax to percentage
for (int i = 0; i < numLines; i++ ) { // Set the running tax amounts
itemPrice[i][2] = itemPrice[i][1] * salesTax;
salesTotal = salesTotal + itemPrice[i][1];
totalTax = totalTax + itemPrice[i][2];
}
//totalTax = salesTotal * salesTax; // Calculate tax
grandTotal = salesTotal + totalTax; // Calculate grand total
// Output:
cls();
cout << "/" << setfill('-') << setw(63) << "-" << "\\" << setfill(' ') << endl;
cout << "| SALES RECEIPT |" << endl;
cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;
cout << "| " << left << setw(32) << "Sales item" << setw(13) << right << "Price" << setw(18) << "Tax |" << endl;
cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;
for ( int i = 0; i <= numLines - 1; ++i ){
cout << "| " << left << setw(32) << itemName[i][1] << "$" << setw(12) << setprecision(2) << fixed << right << itemPrice[i][1] << setw(5) << "$" << setw(11) << itemPrice[i][2] << " |" << endl;
}
cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;
cout << "| Total Sales" << setw(36);
showCurrency(salesTotal);
cout << " |" << endl;
cout << "| Sales Tax (" << setprecision(0) << fixed << taxRate << "%)" << setw(33);
showCurrency(totalTax);
cout << " |" << endl;
cout << "|" << setfill('-') << setw(63) << "-" << "|" << setfill(' ') << endl;
cout << "| Grand Total" << setw(36);
showCurrency(grandTotal);
cout << " |" << endl;
cout << "\\" << setfill('-') << setw(63) << "-" << "/" << setfill(' ') << endl;
cout << endl;
// Clear vars and array for next run:
salesTax = 0.0;
totalTax = 0.0;
salesTotal = 0.0;
grandTotal = 0.0;
memset(itemPrice, 0, sizeof(itemPrice));
memset(itemName, 0, sizeof(itemName));
// Ask if program is to be run again:
bool validResponse = false;
while ( !validResponse ) {
cout << "Would you like to enter a new tax rate (Y/N): ";
cin >> runAgainYN;
if ( toupper(runAgainYN) == 'Y' ) {
validResponse = true;
cin.ignore();
}
else if ( toupper(runAgainYN) == 'N' ) {
runAgain = false;
validResponse = true;
cin.ignore();
}
else {
cout << "INVALID RESPONSE" << endl;
}
}
}
while ( runAgain == true );
return 0;
}
void printLine( int length ) {
for ( int i = 0; i < length; i++ ) {
cout << "=";
}
}
void cls() {
// check OS and run correct clear screen (I do some of my coding in Linux :)
#if (defined (_WIN32) || defined (_WIN64))
system("CLS");
#elif (defined (LINUX) || defined (__linux__))
system("clear");
#endif
}
void showCurrency(double dv, int width){
/* Credit where credit is due:
* The following code snippet was found at https://arachnoid.com/cpptutor/student3.html
* Copyright © 2000, P. Lutus. All rights reserved.
*/
const string radix = ".";
const string thousands = ",";
const string unit = "$";
unsigned long v = (unsigned long) ((dv * 100.0) + .5);
string fmt,digit;
int i = -2;
do {
if(i == 0) {
fmt = radix + fmt;
}
if((i > 0) && (!(i % 3))) {
fmt = thousands + fmt;
}
digit = (v % 10) + '0';
fmt = digit + fmt;
v /= 10;
i++;
}
while((v) || (i < 1));
cout << unit << setw(width) << fmt.c_str();
}
And here is the contents of 'cost.txt':
Books 45.01
Pens 21.03
Pencils 10.90
Hats 50.00
Caps 800.00
Food 1.00
OK looks like i got it. The file operations were within the do loop. I moved them outside of the loop, and it all works. Thanks!
So I have an assignment for a class where I have to convert an employee payroll program into a class. I've completed that part and can even generate an output, but the problem starts there. The output keeps looping. I've had this problem before when I had an earlier program and the way I set the while loop was wrong. But this time, the while statement is fine, but the program still loops. I've corrected other errors but still cannot find this one.
Here is the code I've come up with:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cmath>
#include <cstdlib>
using namespace std;
class payroll {
ifstream fin;
char employeeid[12];
char firstname[20];
char lastname[20];
char SMH;
int SSN, hoursworked, overtimehours;
double hourlyrate, regularpay, overtimepay, grosspay, taxrate, taxamount, netpay, sum, average;
public:
payroll(){
fin.open("employee.txt");
}//CONSTRUCTOR
~payroll();
private:
void calcgrosspay() {
grosspay = regularpay + overtimepay;
if (hoursworked > 40) {
overtimehours = hoursworked - 40;
overtimepay = overtimehours * hourlyrate * 1.5;
regularpay = 40 * hourlyrate;
}//if
else {
overtimehours = 0;
overtimepay = 0;
regularpay = hoursworked * hourlyrate;
}//else
}//for
void calctax() {
if (grosspay >= 500) taxrate = .30;
else if (grosspay>200.00) taxrate = .20;
else taxrate = .10;
if (SMH == 'S' || SMH == 's')
taxrate = taxrate + .05;
taxamount = grosspay*taxrate;
}//for end of grosspay and set taxrate FOR
void calcNetpay() {
netpay = grosspay - taxamount;
}//end of calcnetpay function
void printheadings() {
cout << setw(49) << "-Payroll Report-" << endl;
cout << "------------------------------------------------------------------------------" << endl;
cout << "ID First Name Last Name Stat SSN HW HR OT OP GP Tax Net" << endl;
cout << "==============================================================================" << endl;
cout << "------------------------------------------------------------------------------" << endl;
}//printheadings
void printdata() {
setprecision(2);
cout << setw(14) << employeeid
<< setw(16) << firstname
<< setw(15) << lastname
<< setw(6) << SMH
<< setw(5) << SSN
<< setw(6) << hoursworked
<< setw(6) << hourlyrate
<< setw(8) << grosspay
<< setw(6) << taxrate
<< setw(9) << regularpay
<< setw(6) << overtimehours
<< setw(6) << overtimepay
<< setw(9) << netpay << endl;
}//print data
void payroll::findsum(int i) {
sum += netpay;
}
double payroll::findavg(double, int i) {
average = sum / i;
cout << endl << "The netpay average is " << average << endl;
return average;
}
public:
void printreport() {
int i = 0;
printheadings();
while (fin >> employeeid >> SMH >> SSN >> hoursworked >> hourlyrate >> firstname >> lastname)
{
calcgrosspay();
calctax();
calcNetpay();
printheadings();
printdata();
i++;
findsum(i);
}//while
findavg(sum, i);
}//print data report
}; // end of payroll class
payroll::~payroll() {
fin.close();
}//DESTRUCTOR
int main() {
payroll employee;
employee.printreport();
system("PAUSE");
}//main
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a c++ program I've been working on, it displays student grades from a sequential access file, then uses the same file to calculate and display each students gpa. after calling displayGpa() it says "Run-Time Check Failure #2 - Stack around the variable 'gpa' was corrupted."
Here is the .cpp file giving me trouble:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "sRecords.h"
using namespace std;
void sRecords::displayGpa()
{
string firstName, lastName;
string grade[4];
double gpa[4];
double finalGpa[4];
ifstream inputFile;
inputFile.open("studentRecords.txt");
while (inputFile)
{
inputFile >> firstName >> lastName;
int x = 0;
while (x <=3)
{
inputFile >> grade[x];
if (grade[x] == "A")
{
gpa[x] = 4.00;
}
else if (grade[x] == "A-")
{
gpa[x] = 3.70;
}
else if (grade[x] == "B+")
{
gpa[x] = 3.33;
}
else if (grade[x] == "B")
{
gpa[x] = 3.00;
}
else if (grade[x] == "B-")
{
gpa[x] = 2.70;
}
else if (grade[x] == "C+")
{
gpa[x] = 2.30;
}
else if (grade[x] == "C")
{
gpa[x] = 2.00;
}
else if (grade[x] == "C-")
{
gpa[x] = 1.70;
}
else if (grade[x] == "D+")
{
gpa[x] = 1.30;
}
else if (grade[x] == "D")
{
gpa[x] = 1.00;
}
else if (grade[x] == "D-")
{
gpa[x] = .70;
}
else
{
gpa[x] = 0.00;
}
x++;
}
finalGpa[x] = (gpa[0] + gpa[1] + gpa[2] + gpa[3]) / 4;
cout << firstName << " " << lastName << " " << finalGpa[x] << endl;
}
inputFile.close();
}
void sRecords::displayHeader()
{
cout << "\t-------------------------------" << endl;
cout << "\t\tSTUDENT RECORDS" << endl;
cout << "\t-------------------------------" << endl << endl;
}
void sRecords::printRecords()
{
ifstream inputFile;
inputFile.open("studentRecords.txt");
string string1, string2, string3, string4, string5, string6;
cout << setw(12) << left << "FIRST NAME" << setw(11) << left << "LAST NAME";
cout << setw(9) << left << "ENGLISH" << left << setw(6) << "MATH";
cout << setw(9) << left << "SCIENCE" << left << setw(12) << "CHEMISTRY" << endl << endl;
while (inputFile)
{
inputFile >> string1 >> string2 >> string3 >> string4 >> string5 >> string6;
cout << setw(12) << left << string1 << setw (11) << left << string2;
cout << setw(9) << left << string3 << setw(6) << left << string4;
cout << setw(9) << left << string5 << setw(12) << left << string6 << endl;
}
cout << endl;
inputFile.close();
}
You have an infinite loop - it seems that you got confused about the logic of your inner and outer loop.
It looks like you need to change:
else
{
gpa[x] = 0.00;
} // end of if/else
} // end of inner while loop
finalGpa[x] = (gpa[0] + gpa[1] + gpa[2] + gpa[3]) / 4;
cout << firstName << " " << lastName << " " << finalGpa[x] << endl;
x++;
} // end of outer while loop
to:
else
{
gpa[x] = 0.00;
} // end of if/else
finalGpa[x] = (gpa[0] + gpa[1] + gpa[2] + gpa[3]) / 4;
cout << firstName << " " << lastName << " " << finalGpa[x] << endl;
x++;
} // end of inner while loop
} // end of outer while loop
for some reason my subtotal variable doesn't store the prices of the items inputted by the user any suggestions? I don't know if I set up my loop wrong or if the subtotal has to be put outside the if else statements but then I don't know how I would know what to store from users input
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
const double tax_rate = 0.05;
struct menuItemType
{
string ItemName;
double ItemPrice;
};
void getData(ifstream &in, menuItemType menuList[]);
void showMenu(menuItemType menuList[]);
void printCheck(menuItemType menuList[]);
int main()
{
menuItemType menuList[10];
menuList[10].ItemName;
menuList[10].ItemPrice;
ifstream in;
in.open("Menu.txt");
cout << "Welcome to Johnny's Breakfast Diner!" << endl;
getData(in,menuList);
showMenu(menuList);
return 0;
}
void getData(ifstream &in, menuItemType menuList[])
{
int i = 0;
while (!in.eof())
{
in >> menuList[i].ItemName >> menuList[i].ItemPrice;
i++;
}
}
void showMenu(menuItemType menuList[])
{
int j = 0;
char answ;
cout << fixed << setprecision(2);
cout << "Would you like to take a look at our menu? (Y/N)";
cin >> answ;
if (answ == 'Y' || answ == 'y')
{
cout << left << setw(10) << "Item#" << left << setw(15) << "Item" << left << setw(18) << "Price" << endl;
do {
{
cout << left << setw(8) << j << " " << left << setw(15) << menuList[j].ItemName << " " << "$" << menuList[j].ItemPrice << endl;
j++;
}
} while (j < 8);
printCheck(menuList);
}
else if (answ == 'N' || answ == 'n')
{
system("cls");
cout << "Have a good day!" << endl;
}
}
void printCheck(menuItemType menuList[])
{
char answ;
int choice;
bool menu = true;
double subtotal = 0;
double tax = (subtotal * tax_rate);
double total = (tax + subtotal);
cout << "Would like to place your order (Y/N)";
cin >> answ;
if (answ == 'Y' || answ == 'y')
{
cout << "Please enter the number of the item, 8 to finish order:";
do {
cin >> choice;
if (choice == 0)
{
cout << menuList[0].ItemName << " " << "$" << menuList[0].ItemPrice << endl;
subtotal = subtotal + menuList[0].ItemPrice; \\ for some reason here it doesn't store the prices have no idea why
}
else if (choice == 1)
{
cout << menuList[1].ItemName << " " << "$" << menuList[1].ItemPrice << endl;
subtotal = subtotal + menuList[1].ItemPrice;
}
else if (choice == 2)
{
cout << menuList[2].ItemName << " " << "$" << menuList[2].ItemPrice << endl;
subtotal = subtotal + menuList[2].ItemPrice;
}
else if (choice == 3)
{
cout << menuList[3].ItemName << " " << "$" << menuList[3].ItemPrice << endl;
subtotal = subtotal + menuList[3].ItemPrice;
}
else if (choice == 4)
{
cout << menuList[4].ItemName << " " << "$" << menuList[4].ItemPrice << endl;
subtotal = subtotal + menuList[4].ItemPrice;
}
else if (choice == 5)
{
cout << menuList[5].ItemName << " " << "$" << menuList[5].ItemPrice << endl;
subtotal = subtotal + menuList[5].ItemPrice;
}
else if (choice == 6)
{
cout << menuList[6].ItemName << " " << "$" << menuList[6].ItemPrice << endl;
subtotal = subtotal + menuList[6].ItemPrice;
}
else if (choice == 7)
{
cout << menuList[7].ItemName << " " << "$" << menuList[7].ItemPrice << endl;
subtotal = subtotal + menuList[7].ItemPrice;
}
else if (choice == 8)
{
break;
}
}while(menu = true);
cout << "Taxes" << "$" << tax << endl;
cout << "Amount Due" << "$" << total << endl;
}
else if (answ == 'N' || answ == 'n')
{
system("cls");
cout << "Ok, maybe I can help you at a later time." << endl;
}
}
It looks like you're trying to use subtotal before you've actually put data into it.
The problem is these lines:
double tax = (subtotal * tax_rate);
double total = (tax + subtotal);
At that point in the program, subtotal still contains the initial value, which is 0, so the result of those calculations is also 0. You need to put those lines after the loop so that they work with the final value of subtotal.
What's the result. the subtotal will have
menuList[choice].ItemPrice value
if you want to change
subtotal += menuList[choice].ItemPrice;
The output for this program, thanks to you guys, is fixed. Except for the studentNumber. I read the comment that I never set a value to it and that confused me.
void process_file(ifstream& input)
{
int thisStudent = 0;
StudentRecord student = StudentRecord();
while (thisStudent++ < CLASS_SIZE)
{
student.input(input, thisStudent);
student.computeGrade();
student.output();
}
}
would this not set studentNumber equal to 0 then add +1 every time it runs through the loop.
// Author:
// Assignment 8
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
ofstream outputfile("output.txt");
const int MAX_FILE_NAME = 35;
const int CLASS_SIZE = 5;
class StudentRecord
{
public:
void input( ifstream& input,int studentid);
void computeGrade();
void output();
private:
int studentNumber;
double exam1;
double exam2;
double exam3;
double exam4;
double average;
char grade;
};
void open_input(ifstream& input, char name[]);
void process_file(ifstream& input);
int main()
{ char again;
char file_name[MAX_FILE_NAME + 1];
ifstream input_numbers;
cout << "This program can calculate the exam average and grade for\n"
<< "each student.\n" << endl;
system("pause");
do
{
system("cls");
open_input(input_numbers, file_name);
process_file(input_numbers);
input_numbers.close();
cout << "\nDo you want to process another file (Y/N)? ";
cin >> again;
cin.ignore(256, '\n');
} while ( again == 'y' || again == 'Y');
cout << "\nEnd of Program!" << endl;
outputfile << "\n\nThanks for using GradeCalc!\f";
outputfile.close();
return 0;
}
void process_file(ifstream& input)
{
int thisStudent = 0;
StudentRecord student = StudentRecord();
while (thisStudent++ < CLASS_SIZE)
{
student.input(input, thisStudent);
student.computeGrade();
student.output();
}
}
void open_input(ifstream& input, char name[])
{ int count = 0;
do
{ count++;
if (count != 1)
{ cout << "\n\aInvalid file name or file does not exist. Please try again."
<< endl;
}
cout << "\nEnter the input file name (maximum of " << MAX_FILE_NAME
<< " characters please)\n:> ";
cin.get(name, MAX_FILE_NAME + 1);
cin.ignore(256, '\n');
input.clear();
input.open(name,ios_base::in);
} while (input.fail() );
}
void StudentRecord::input(ifstream& input, int studentid)
{
input >> exam1 >> exam2 >> exam3 >> exam4;
}
void StudentRecord::computeGrade()
{
average = (exam1 + exam2 + exam3 + exam4) / 4 ;
if (average >= 90)
grade = 'A';
else if (average >= 80)
grade = 'B';
else if (average >= 70)
grade = 'C';
else if (average >= 60)
grade = 'D';
else if (average < 60)
grade = 'F';
}
void StudentRecord::output()
{
cout << "\n\nThe record for student number:" << setw(8) << studentNumber << endl;
cout << "The exam grades are:" << setw(8) << exam1 << exam2 << exam3 << exam4 << endl;
cout << "The numeric average is:" << setw(8) << average << endl;
cout << "and the letter grade assigned is:" << setw(8) << grade << endl;
}
Well, studentNumber is garbage because you never put a value in it. So it just has whatever happened to already be in memory at that location.
The exam grades print out wrong because commas in C++ don't do what you think they do, and that's also why adding an endl; to it gives you an error.
The formatting I'm going to let you work out for yourself. You should consider reading up on output or at least doing some trial and error.
One of the errors is that instead of this:
cout << "The exam grades are:" << setw(8) << exam1, exam2, exam3, exam4;
I think you mean this:
cout << "The exam grades are:" << setw(8) << exam1 << exam2 << exam3 << exam4 << endl;
CLASS_SIZE is defined as 5, so this loop:
while (thisStudent++ < CLASS_SIZE)
will iterate 6 times.
Also
cout << "The exam grades are:" << setw(8) << exam1, exam2, exam3, exam4;
This outputs exam1, and then evaluates and does nothing with the rest of the variables.
70 80 90 95 95 85 90 80 75 85 70 80 55 85 50 70 45 50 40 35
does it have the spaces? If yes, you need to ignore them. input >> exam1 >> exam2 >> exam3 >> exam4; would load space into one of the exam variables.
-- edit for MooingDuck --
#include <iostream>
#include <sstream>
using namespace std;
int main() {
cout << "main() ENTRY" << endl;
stringstream s1(ios_base::in | ios_base::out),
s2(ios_base::in | ios_base::out);
int i = -1;
s1 << "111 222";
s1 >> i; cout << i << endl;
s1 >> i; cout << i << endl;
s2 << "111 222";
s2 >> noskipws;
s2 >> i; cout << i << endl;
s2 >> i; cout << i << endl;
return 0;
}
Output:
main() ENTRY
111
222
111
0