Second Line of Text File Not Reading; C++; Visual Studio - c++

I am in a second-year computer science class and we are learning C++.
The assignment is to write a text file and calculate totals and averages based on the text file's data.
This is what my text file looks like:
Angela Langston Maya Malcolm Total Average
Algebra 64.5 56.7 67.4 90.0
CS1 88.6 77.0 55.3 89.4
English 91.3 67.4 89.0 100.0
Science 100.0 89.4 80.2 91.4
Average
I was doing just fine until I compiled and debugged. My program will not print the second line of my text file correctly. It prints out:
-107374176.0 -107374176.0 -107374176.0 -107374176.0 -429496704.0 -107374176.0
instead of the data I have stored in the text file.
Please help. I'll provide any additional information that is needed to solve this problem. Also, just a reminder, I am a beginner C++ user.
Update:
Here's the code:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
void student_heading();
void report_heading();
float average_calc(float);
int main()
{
cout << fixed << showpoint << setprecision(1);
string name1, name2, name3, name4;
string title1, title2;
string class1, class2, class3, class4, title3;
string fecha;
float algebra1, cs1, english1, science1;
float algebra2, cs2, english2, science2;
float algebra3, cs3, english3, science3;
float algebra4, cs4, english4, science4;
float algebra_total;
algebra_total = 0;
float cs_total = 0;
cs_total = 0;
float english_total = 0;
english_total = 0;
float science_total;
science_total = 0;
float algebra_avg, cs_avg, english_avg, science_avg;
float angela_avg, langston_avg, maya_avg, malcolm_avg;
float angela_total, langston_total, maya_total, malcolm_total;
angela_total = algebra1 + cs1 + english1 + science1;
langston_total = algebra2 + cs2 + english2 + science2;
maya_total = algebra3 + cs3 + english3 + science3;
malcolm_total = algebra4 + cs4 + english4 + science4;
angela_avg = average_calc(angela_total);
langston_avg = average_calc(langston_total);
maya_avg = average_calc(maya_total);
malcolm_avg = average_calc(malcolm_total);
student_heading();
cout << "What is today's date? (Example: May 1, 1996 = 05/01/1996): " << endl;
cin >> fecha;
cout << "DATE:" << fecha << "*************************************************** Page 1" << endl;
report_heading();
ifstream inData;
inData.open("infile.txt");
inData >> name1 >> name2 >> name3 >> name4 >> title1 >> title2;
cout << " " << name1 << " " << name2 << " " << name3 << " " << name4 << " " << title1 << " " << title2 << endl;
inData >> class1 >> algebra1 >> algebra2 >> algebra3 >> algebra4 >> algebra_total >> algebra_avg;
algebra_total = algebra1 + algebra2 + algebra3 + algebra4;
algebra_avg = average_calc(algebra_total);
cout << class1 << " " << algebra1 << " " << algebra2 << " " << algebra3 << " " << algebra4 << " " << algebra_total << " " << algebra_avg << endl;
inData >> class2 >> cs1 >> cs2 >> cs3 >> cs4 >> cs_total >> cs_avg;
cs_total = cs1 + cs2 + cs3 + cs4;
cs_avg = average_calc(cs_total);
cout << class2 << " " << cs1 << " " << cs2 << " " << cs3 << " " << cs4 << " " << cs_total << " " << cs_avg << endl;
inData >> class3 >> english1 >> english2 >> english3 >> english4 >> english_total >> english_avg;
english_total = english1 + english2 + english3 + english4;
english_avg = average_calc(english_total);
cout << class3 << english1 << english2 << english3 << english4 << english_total << english_avg;
inData >> class4 >> science1 >> science2 >> science3 >> science4 >> science_total >> science_avg;
science_total = science1 + science2 + science3 + science4;
science_avg = average_calc(science_total);
cout << class4 << science1 << science2 << science3 << science4 << science_total << science_avg;
inData >> title3;
cout << title3 << angela_avg << langston_avg << maya_avg << malcolm_avg << endl;
inData.close();
return 0;
}
void report_heading()
{
cout << "********************SMALL COLLEGE GRADE REPORT*******************" << endl;
}
void student_heading()
{
cout << "*******************" << endl;
cout << "Student" << endl;
cout << "ID" << endl;
cout << "SYCS-135 Computer Science I" << endl;
cout << "Assignment 5" << endl;
cout << "September 24, 2015" << endl;
cout << "******************" << endl;
}
float average_calc(float total_value)
{
float average;
average = total_value / 4;
return average;

This line
inData >> class1 >> algebra1 >> algebra2 >> algebra3 >> algebra4 >> algebra_total >> algebra_avg;
attempts to read the string "CS1" into algebra_total, which causes the stream to fail. Either don't attempt to read those numbers, or fix your text file to something like
Angela Langston Maya Malcolm Total Average
Algebra 64.5 56.7 67.4 90.0 0 0
CS1 88.6 77.0 55.3 89.4 0 0
English 91.3 67.4 89.0 100.0 0 0
Science 100.0 89.4 80.2 91.4 0 0
Average

Related

Salary with vector array to get sum of employee gross pay

I am to create an application that takes at least 5 employees i.d, names, pay rate, and hours. And then I am to add the pay rate and the hours together to show the gross pay for each employee at the end of the initial inquiries. I am stuck on how to add it in the vector please help!
** Here is the assignment that our instructor gave us **
http://itweb.fvtc.edu/ag/?u=3&f=cpp-assignment4
I've added a vector and added all the essential information for the employee
#include <iostream>
#include <conio.h>
#include <string>
#include <vector>
using namespace std;
struct Employee
{
int id;
string firstName;
string lastName;
float payRate;
int hours;
};
int main()
{
/*========= other way of adding employee information ==========*/
/*const int NUM_EMPLOYEE = 5;
Employee employee[NUM_EMPLOYEE];
for (int i = 0; i < 5; i++)
{
cout << "ID of employee " << (i + 1) << ": ";
cin >> employee[i].id;
cout << "First Name of employee " << (i + 1) << ": ";
cin >> employee[i].firstName;
cout << "Last Name of employee " << (i + 1) << ": ";
cin >> employee[i].lastName;
cout << "Pay rate for employee " << (i + 1) << ": ";
cin >> employee[i].payRate;
cout << "Hours worked " << (i + 1) << ": ";
cin >> employee[i].hours;
}*/
/*========= End of other way of adding employee information ==========*/
vector<Employee> employees;
char Another = 'y';
while (Another == 'y' || Another == 'Y')
{
Employee e;
cout << "Enter employee ID: \n";
cin >> e.id;
cout << "Enter employee first name: \n";
cin >> e.firstName;
cout << "Enter employee last name: \n";
cin >> e.lastName;
cout << "Enter employee pay rate: \n";
cin >> e.payRate;
cout << "Enter employee hours worked: \n";
cin >> e.hours;
employees.push_back(e);
cout << "Another? (y/n): \n";
cin >> Another;
}
float sum = 0;
vector<Employee>::iterator it = employees.begin();
for (; it != employees.end(); it++)
{
cout << "ID of employee: \n" << it->id << ": \n"
<< "Employees name: \n" << it->firstName << " " << it->lastName << ": \n"
<< "Employee pay rate: \n" << it->payRate << ": \n"
<< "Employee hours worked: \n" << it->hours << "\n";
}
float avg = sum / employees.size();
Employee e;
/*cout << " ID of employees: \n" << e.id;
cout << " Name of employees: \n" << e.firstName << " " <<
e.lastName;*/
cout << "Gross pay of employees: \n" << avg;
_getch();
return 0;
}
Show Id, names, and gross pay of all employees to user
vector<Employee> employees;
char Another = 'y';
while (Another == 'y' || Another == 'Y')
{
Employee e;
cout << "Enter employee ID: \n";
cin >> e.id;
cout << "Enter employee first name: \n";
cin >> e.firstName;
cout << "Enter employee last name: \n";
cin >> e.lastName;
cout << "Enter employee pay rate: \n";
cin >> e.payRate;
cout << "Enter employee hours worked: \n";
cin >> e.hours;
employees.push_back(e);
cout << "Another? (y/n): \n";
cin >> Another;
}
float sum = 0;
vector<Employee>::iterator it = employees.begin();
cout << "ID" << "\t" << "First Name" << "\t" << "Last Name" << "\t" << "Pay rate" << "\t" << "Hours" << "\t" << "Gross Pay" << "\n" ;
for (; it != employees.end(); it++)
{
float grossPay = it->payRate * it->hours;
cout << it->id << "\t" << it->firstName << "\t\t" << it->lastName << "\t\t" << it->payRate << "\t\t"
<< it->hours << "$" << "\t" << grossPay << "\n";
sum += grossPay;
}
cout << "The gross pay for all employee is: " << "$" << sum;
_getch();
return 0;
}
//This is what i got so far. But if I want to make the application ask the user to input how many employee they want to enter into the database how do i do that? would it be like this?
int EMPLOYEE_NUM[][] // ??

C++ textfile reading infinite whileloop

I am doing C++ program which reads infinite while loop,
After letting user enter the desired month and year.
The loop become infinite and only output "AAAAA...."
Textfile(input)
1 9 2017|0112233445|20.00 5.00 2 9 2017|0123456789|6.00 3.00
3 10 2017|0135792468|30.00 1.00 4 10 2017|0166778899|7.00
10.00 4 10 2017|0177001228|40.00 4.00 5 10 2017|0184040626|8.00 2.00 6 10 2017|0134567892|50.00 6.00 7
10 2017|0145678910|9.00 7.00
I tried using while(inS >> Day>>Month >> Year >> ch >>hpNO >> ch >> c_Charges >> sms_charges )
but nothing seems to be worked .Any suggestions to solve this problem?Thanks in advance.
void monthlyreport(char manager[])
{
SYSTEMTIME T;
GetSystemTime(&T);
int month, year; //userinput
char ch;//store delimitor
int count = 0;
double Totalcallcharges = 0;
double Totalsmscharges = 0;
double Totalcharges = 0;
int Day,Month, Year;//for textfile reading
char hpNO[11];
double c_Charges =0;
double sms_charges =0;
string Months[] = { "January","February","March","April","May","June","July","August","September","October","November","December" };
system("cls");
cout << "You choose : MONTHLY CHARGES REPORT ...";
cout << "\n\n Which month/year (mm yyyy)? ";
cin >> month;
cin >> year;
ifstream inS;
inS.open("Transaction.txt");
/*while (inS >> Day)
{
while (inS >> Month)
{
while (inS >> Year)
{
while (inS >> ch)
{
while (inS >> hpNO)
{
while (inS >> ch)
{
while (inS >> c_Charges)
{
while (inS >> sms_charges)
{
if (month == Month && year == Year)
{
Totalcallcharges += c_Charges;
}
if (month == Month && year == Year)
{
Totalsmscharges += sms_charges;
}
count++;
}
}
}
}
}
}
}
}
*/
while (!inS.eof()) correct answer
{
inS >> tranS.day >> tranS.month >> tranS.year >> ch;
inS.getline(tranS.phoneNO, 12, '|');
inS >> tranS.call_charges >> tranS.sms_charges;
transactions(&head, tranS);
if (tranS.month == month &&tranS.year == year)
{
tranS.Total_call_charges += tranS.call_charges;
tranS.Total_sms_charges += tranS.sms_charges;
}
count++;
}
Totalcharges = Totalcallcharges + Totalsmscharges;
inS.close();
system("cls");
cout << Month << year;
cout << endl << c_Charges;
cout << setw(50) << setfill('=') << " " << endl << endl;
cout << " T A R U C M O B I L E S D N B H D" << endl << endl;
cout << setfill(' ') << setw(30) << "Monthly Report - " << Months[month - 1] << " " << year << endl;
cout << "\nTotal Number of TARUCMOBILE users = " << count;
cout << "\n\nTotal Charges from Calls = RM" << setw(8) << setfill(' ') << Totalcallcharges << setprecision(2);
cout << "\nTotal Charges from SMS's = RM" << setw(8) << setfill(' ') << Totalsmscharges << setprecision(2);
cout << "\n" << setfill(' ') << setw(27) << " " << right << setw(12) << setfill('-') << "-" << endl;
cout << "TOTAL CHARGES (POSTPAID) = RM" << setw(8) << setfill(' ') << Totalcharges << setprecision(2);
cout << "\n" << setw(27) << setfill(' ') << " " << setw(12) << setfill('=') << "=" << endl;
cout << "*** E N D O F R E P O R T *** " << endl << endl;
cout << "Generated by" << endl;
cout << "______________" << endl;
cout << manager << "(Manager)" << endl;
cout << T.wDay << " " << Months[T.wMonth - 1] << " " << T.wYear << endl;
cout << endl << setw(50) << setfill('=') << " " << endl;
system("pause");
}
Try
while(inS >> Day)
{
while(inS >> Month)
{
while(inS >> Year)
{
while(inS >>ch)
{
.
.
.
}
Then do whatever you want to inside the innermost while loop.

Beginner C++ input behviour

This program is a very simple code in my practice to learn C++. The problem is at some point it does not accept input from cin and behaves strangely.
The code and the output of the program are below.
Why does the program not consider cin at "Enter your first name please"?
# include "cmath"
# include <iostream>
using namespace std;
int main()
{
string FirstName, MiddleName, LastName;
string WelcomeMessage = "Welcome to Visual C++";
int Number_of_Steps = 5;
int LoopStart = 1, LoopEnd = 5;
int AgeYears, AgeMonths;
double Pi = 3.14;
float k = 5.366;
double Age;
char* Symbol = "k";
bool TestResult = true;
MiddleName = "Milton";
cout << "Input Your First Name and Last Name" << endl;
cin >> FirstName >> LastName;
cout << "Input your Age in Years" << endl;
cin >> AgeYears;
cout << "Imput your Age in Months " << endl;
cin >> AgeMonths;
Age = AgeYears + AgeMonths / 12;
cout << endl << "Your Name is " << FirstName << ' ' << LastName << endl;
cout << "Your Age is " << Age << endl;
cout << "The Character is " << Symbol << endl;
// Testing operators
cout << "Please Enter a floating point number \n";
int n;
cin >> n;
cout << "n==" << n
<< "\n n+1==" << n + 1
<< "\n n three times==" << 3 * n
<< "\n n twice ==" << n + n
<< "\n nsquared ==" << n*n
<< "\n half of n ==" << n / 2
<< "\n square root of n ==" << sqrt(n)
<< "\n";
// Testing string addition
cout << "Eneter your first name please" << endl;
string String1, String2, String3;
cin >> String1;
cout << "Enter your family name please" << endl;
cin >> String2;
String3 = String1 + " " + String2;
cout << "Welcome" << " " << String3 << endl;
// testing inequalities to strings
string FirstString, SecondString;
cout << "Input First String "
<< endl;
cin >> FirstString;
cout << "Input Second String "
<< endl;
cin >> SecondString;
if (FirstString == SecondString)
cout << "The two words are identical \n";
if (FirstString >= SecondString)
cout << "First word is bigger than second word \n";
if (FirstString <= SecondString)
cout << "Second word is bigger than first word \n";
}
You get a hint from the output displaying .2 as the first name (String1). The cin operation before asking for first name had 64.2 on the buffer but because you read the value into an int n it only read the integer portion 64 and left the .2 on the buffer. Changing the declaration n to float n or doing some input validation if you did want an integer should leave the buffer empty when you get to the request for first name.

c++ infile extraction checking if int

I'm fairly new to C++ and have no idea where to start with this or if its even possible, but i'm trying to check to see if length, width, radius, etc are actually doubles and if they are not return 0.
int main() {
ifstream inFile;
ofstream outFile;
string in;
double length, width, tLength = 0, tWidth = 0, areaRec, tAreaRec = 0, parameter, tParameter = 0;
double radius, tRadius = 0, areaCirc, tAreaCirc = 0, circumference, tCircumference = 0;
double savings, tSavings = 0;
int people = 0, age, tAge = 0;
string name1, name2;
inFile.open("inData_with_error.txt");
outFile.open("outData_Normal.txt");
outFile << fixed << showpoint << setprecision(2);
if (!inFile) {
cout << "ERROR: Unable to open file!" << endl;
inFile.close();
}
else {
cout << "Caculating..." << endl;
while (inFile >> length >> width >> radius >> name1 >> name2 >> age >> savings) {
cout << length << ", " << width << ", " << radius << ", " << name1 << ", " << name2 << ", " << age << ", " << savings << endl;
tLength = tLength + length;
tWidth = tWidth + width;
parameter = length * 2 + width * 2;
areaRec = length * width;
tParameter = tParameter + parameter;
tAreaRec = tAreaRec + areaRec;
tRadius = tRadius + radius;
areaCirc = pow(radius, 2) * PI;
circumference = (radius * 2) * PI;
tAreaCirc = tAreaCirc + areaCirc;
tCircumference = tCircumference + circumference;
people = people + 1;
tAge = tAge + age;
tSavings = tSavings + savings;
}
}
cout << "Done" << endl;
outFile << "Rectangle:" << endl << "Total length = " << tLength << ", " << "Total width = " << tWidth << ", " << "Total area = " << tAreaRec << ", " << "Total parameter = " << tParameter << endl << endl
<< "Circle:" << endl << "Total radius = " << tRadius << ", " << "Total area = " << tAreaCirc << ", " << "Total circumference = " << tCircumference << endl << endl
<< "Person: " << endl << "Total number of persons = " << people << endl << "Total age = " << tAge << endl << "Total savings = " << tSavings << endl;
inFile.close();
outFile.close();
system("pause");
return 0;
}
For example if my data with error is the below i want to catch the char and strings and return a 0 but have no idea how to tackle this question. Can someone lead me into the right direction?
10.45 aaaa
13.78
Jake Melon 45
7600
128 76.9
;
Mike Sander 23
800
15.9 43
w
David James i
87000.54
After the end of the while loop, you can add a test to check to whether the while loop got terminated due to EOF or due to an error in reading the data.
while (inFile >> length >> width >> radius >> name1 >> name2 >> age >> savings) { ... }
if ( inFile.eof() )
{
// No errors in reading data
}
else
{
// Error in reading data.
// Deal with error
}

Array not initializing properly within a while loop

My issue is that I have set up an array to store totals that were calculated from values read from a file. These stored totals are then added together to find the over all average.
This issue is stemming from a 'cin' at the beginning of the program where the user inputs a number and that number is supposed to drive the program by setting how many times the program loops and how many modules are inside the array. The array does not seem to work properly no matter how much I try.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string StudentGrades;
int studentID;
double quiz1;
double quiz2;
double quiz3;
double quiz4;
int total = 0;
double choice;
ofstream outFile;
double numStud=1;
cout << "Enter student ID number, Quiz 1 Grade, Quiz 2 Grade , Quiz 3 Grade, Quiz 4 Grade" << endl;
outFile.open("StudentGrades.txt");
cout << "How many students would you like to enter?" << endl;
cin >> numStud;
for (int x = 0; x < numStud; x++)
{
cout << "Enter student ID: ";
cin >> studentID;
cout << "Enter quiz grade 1: ";
cin >> quiz1;
//cout << quiz1;
cout << "Enter quiz grade 2: ";
cin >> quiz2;
//cout << quiz2;
cout << "Enter quiz grade 3: ";
cin >> quiz3;
//cout << quiz3;
cout << "Enter quiz grade 4: ";
cin >> quiz4;
//cout << quiz4;
cout << endl;
//outFile.open("StudentGrades.txt");
if (outFile.is_open())
{
cout << "inside if/else outFile" << endl;
//outFile << "File successfully open";
outFile << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
}
else
{
cout << "Error opening file";
}
outFile.close();
/*cout << "Enter 0 for no more students. Enter 1 for more students." << endl;
cin >> choice;
if (choice == 1)
continue;
if (choice == 0)
{
outFile.close();
break;
}*/
}
ifstream inFile;
inFile.open("StudentGrades.txt");
int sTotal;
int total[numStud];
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
total = (quiz1 + quiz2 + quiz3 + quiz4);
sTotal = total[numStud];
double avg = total / 4;
}
system("pause");
return 0;
}
int total[numStud]; is a variable length array and is not standard in C++. If you need an array and you don't know what the size will be then you should use a std::vector. A vector can be used almost exactly as an array can. For example you could would become:
int total;
std::vector<int> studentTotal;
while (inFile >> studentID >> quiz1 >> quiz2 >> quiz3 >> quiz4)
{
//cout << studentID << " " << quiz1 << " " << quiz2 << " " << quiz3 << " " << quiz4 << endl;
studentTotal.push_back(quiz1 + quiz2 + quiz3 + quiz4); // insert into the vector at the end
total += studentTotal.back(); // get last inserted element
}