At the moment I am using ifstream to read multiple files, like this:
File1:
name - cost
File2:
name - cost
File3:
name - cost
I am wanting to put all the files into one big file and use ifstream to read it line by line. What would I need to do this?
Here is my code:
//Lawn
int lawnLength;
int lawnWidth;
int lawnTime = 20;
float lawnCost;
string lawnName;
ifstream lawn;
lawn.open("lawnprice.txt");
lawn >> lawnName >> lawnCost;
cout << "Length of lawn required: "; // Asks for the length
cin >> lawnLength; // Writes to variable
cout << "Width of lawn required: "; // Asks for the width
cin >> lawnWidth; // Writes to variable
int lawnArea = (lawnLength * lawnWidth); //Calculates the total area
cout << endl << "Area of lawn required is " << lawnArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (lawnArea * lawnCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (lawnArea * lawnTime) << " minutes" << endl << endl; //Prints total time
int totalLawnTime = (lawnArea * lawnTime);
//Concrete Patio
int concreteLength;
int concreteWidth;
int concreteTime = 20;
float concreteCost;
string concreteName;
ifstream concrete;
concrete.open("concreteprice.txt");
concrete >> concreteName >> concreteCost;
cout << "Length of concrete required: "; // Asks for the length
cin >> concreteLength; // Writes to variable
cout << "Width of concrete required: "; // Asks for the width
cin >> concreteWidth; // Writes to variable
int concreteArea = (concreteLength * concreteWidth); //Calculates the total area
cout << endl << "Area of concrete required is " << concreteArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (concreteArea * concreteCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (concreteArea * concreteTime) << " minutes" << endl << endl; //Prints total time
int totalConcreteTime = (concreteArea * concreteTime);
If everything is in 1 file, your solution will involve a loop:
std::string line;
while (std::getline(fin, line))
{
...
}
And each line should be parsed to get the data you expect:
std::istringstream iss(line);
std::string name;
float cost;
if (!(iss >> name >> cost))
{
// some error occurred, handle it
}
else
{
// do something with the valid data
}
Related
I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
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.
I need help understanding the [Error] id return 1 exit status due to 2 undefined references: getGrades() and getAverage(). I was issued DEV C++ and knocked out the syntax errors with mild frustration but these "linking" errors are still giving me a hard time. This is the most recent update of the code, if anyone could help me understand these linking errors that would be great.
Compiler - Dev C++
Windows 7
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// Function declarations
string getStudentName();
string getWork();
int getGrades();
double getAverage();
int main()
{
string studentName, work[3];
int grades[3];
double average;
// Get the name of the student
studentName = getStudentName();
// Get the work
work[3] = getWork();
// Get the grades
grades[3] = getGrades();
// Get the average
average = getAverage();
// Dynamic spacing for grades
ostringstream ss;
int gradesLength = ss.str().length();
ss <<setprecision(0) << fixed << showpoint;
ss << grades;
cout << "\n the average for " << studentName << " is: " << average << endl;
cout << "The grades for " << studentName << " are: " << endl;
cout << setw(30) << work[0] << ": " << setw(gradesLength) << grades[0] << endl;
cout << setw(30) << work[1] << ": " << setw(gradesLength) << grades[1] << endl;
cout << setw(30) << work[2] << ": " << setw(gradesLength) << grades[2] << "\n\n\n";
cout << "You have completed the program: \n";
return 0;
}
// Student Name
string getStudentName()
{
string name;
cout << "Enter students full name: ";
getline(cin, name);
return name;
}
// Assignments
string getWork()
{
string work[3];
cout << "\nEnter the name of each assignment \n";
cout << "First assignment: ";
getline (cin, work[0]);
cout << "Second assignment: ";
getline (cin, work[1]);
cout << "Third assignment: ";
getline (cin, work[2]);
return work[3];
}
// Grades
int getGrades(string work[3])
{
int grades[3];
cout << "\nEnter the grade for " << work[0] << ": ";
cin >> grades[0];
cout << "Enter the grade for " << work[1] << ": ";
cin >> grades[1];
cout << "Enter the grade for " << work[2] << ": ";
cin >> grades[2];
return grades[3];
}
// Math
double getAverage(int grades[3])
{
double average;
average = (grades[0] + grades[1] + grades[2]) / 3.0f;
return average;
}
This question already has answers here:
Getting input from external files?
(4 answers)
Closed 9 years ago.
Basically, I need a basic .txt -- maybe a .csv -- file that is going to be read by the program and use a number located in the file.
I would want the file to look like this:
oranges: 1.50
apples: 2.10
pears: 4.70
I would then want the program to read 1.50 from the first line and assign that to the variable orangeCost. I would then want the second part to read the second line and assign 2.10 to the variable apples, etc.
This is what I have so far:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
int garden();
//Lawn
int lawnLength;
int lawnWidth;
int lawnTime = 20;
float lawnCost = 15.50;
cout << "Length of lawn required: "; // Asks for the length
cin >> lawnLength; // Writes to variable
cout << "Width of lawn required: "; // Asks for the width
cin >> lawnWidth; // Writes to variable
int lawnArea = (lawnLength * lawnWidth); //Calculates the total area
cout << endl << "Area of lawn required is " << lawnArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (lawnArea * lawnCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (lawnArea * lawnTime) << " minutes" << endl << endl; //Prints total time
//Concrete Patio
int concreteLength;
int concreteWidth;
int concreteTime = 20;
float concreteCost = 20.99;
cout << "Length of concrete required: "; // Asks for the length
cin >> concreteLength; // Writes to variable
cout << "Width of concrete required: "; // Asks for the width
cin >> concreteWidth; // Writes to variable
int concreteArea = (concreteLength * concreteWidth); //Calculates the total area
cout << endl << "Area of concrete required is " << concreteArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (concreteArea * concreteCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (concreteArea * concreteTime) << " minutes" << endl << endl; //Prints total time
//Wooden Deck
int woodenDeckLength;
int woodenDeckWidth;
int woodenDeckTime = 30;
float woodenDeckCost = 15.75;
cout << "Length of wooden deck required: "; // Asks for the length
cin >> woodenDeckLength; // Writes to variable
cout << "Width of wooden deck required: "; // Asks for the width
cin >> woodenDeckWidth; // Writes to variable
int woodenDeckArea = (woodenDeckLength * woodenDeckWidth); //Calculates the total area
cout << endl << "Area of wooden deck required is " << woodenDeckArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (woodenDeckArea * woodenDeckCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (woodenDeckArea * woodenDeckTime) << " minutes" << endl << endl; //Prints total time
//Rectangular Pond
int rectangularPondLength;
int rectangularPondWidth;
int rectangularPondTime = 45;
float rectangularPondCost = 25.00;
cout << "Length of rectangular pond required: "; // Asks for the length
cin >> rectangularPondLength; // Writes to variable
cout << "Width of rectangular pond required: "; // Asks for the width
cin >> rectangularPondWidth; // Writes to variable
int rectangularPondArea = (rectangularPondLength * rectangularPondWidth); //Calculates the total area
cout << endl << "Area of rectangular pond required is " << rectangularPondArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (rectangularPondArea * rectangularPondCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (rectangularPondArea * rectangularPondTime) << " minutes" << endl << endl; //Prints total time
//Water Features
int waterFeatures;
int waterFeaturesTime = 60;
float waterFeaturesCost = 150.00;
cout << "Number of water features required: "; // Asks for the amount of water features needed
cin >> waterFeatures; // Writes to variable
cout << endl << "Number of water feature(s) required is " << waterFeatures << " water feature(s)"; //Prints the total area
cout << endl << "This will cost a total of " << (waterFeatures * waterFeaturesCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (waterFeatures * waterFeaturesTime) << " minutes" << endl << endl; //Prints total time
//Garden Lights
int gardenLights;
int gardenLightsTime = 10;
float gardenLightsCosts = 5.00;
cout << "Number of garden lights required: "; // Asks for the amount of water features needed
cin >> gardenLights; // Writes to variable
cout << endl << "Number of garden light(s) required is " << gardenLights << " garden light(s)"; //Prints the total area
cout << endl << "This will cost a total of " << (gardenLights * gardenLightsCosts) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (gardenLights* gardenLightsTime) << " minutes" << endl << endl; //Prints total time
//Quotation
string quotation;
cout << "Do you want to save a quotation? " << endl; //Asks if they want to save a quotation
cin >> quotation; //Saves if they want to save a quotation or not
if (quotation == "yes")
{
std::string nameOfFile;
cout << "What would you like to save the quotation as? (Maybe using your last name) " << endl;
cin >> nameOfFile;
ofstream outfile(nameOfFile + ".txt"); // Opens file in write mode
//Lawn
outfile << "The total lawn area is " << lawnArea << " square meters" << endl; // Writes users data into the file
outfile << "The total cost for the lawn is £" << (lawnArea * lawnCost) << endl; // Writes users data into the file
outfile << "The total time for the lawn is " << (lawnArea * lawnTime) << " minutes" << endl << endl; // Writes users data into the file
//Concrete Patio
outfile << "The total concrete patio area is " << concreteArea << " square meters" << endl;
outfile << "The total cost for the concrete patio is £" << (concreteArea * concreteCost) << endl;
outfile << "The total time for the concrete patio is " << (concreteArea * concreteTime) << " minutes" << endl << endl;
//Wooden Deck
outfile << "The total wooden deck area is " << woodenDeckArea << " square meters" << endl;
outfile << "The total cost for the wooden deck is £" << (woodenDeckArea * woodenDeckCost) << endl;
outfile << "The total time for the wooden deck is " << (woodenDeckArea * woodenDeckTime) << " minutes" << endl << endl;
//Rectangular Pond
outfile << "The total rectangular pond area is " << rectangularPondArea << " square meters" << endl;
outfile << "The total cost for the wooden deck is £" << (rectangularPondArea * rectangularPondCost) << endl;
outfile << "The total time for the wooden deck is " << (rectangularPondArea * rectangularPondTime) << " minutes" << endl << endl;
//Water Features
outfile << "The total number of water feature(s) needed are " << waterFeatures << endl;
outfile << "The total cost for the water feature(s) is £" << (waterFeatures * waterFeaturesCost) << endl;
outfile << "The total time for the water feature(s) is " << (waterFeatures * waterFeaturesTime) << " minutes" << endl << endl;
//Garden Lights
outfile << "The total number of garden light(s) needed are " << gardenLights << endl;
outfile << "The total cost for the garden light(s) is £" << (gardenLights * gardenLightsCosts) << endl;
outfile << "The total time for the garden light(s) is " << (waterFeatures * waterFeaturesTime) << " minutes" << endl << endl;
//CLOSE FILE
outfile.close(); // Close's the file.
cout << "Quotation saved." << endl;
}
else
{
cout << "Quotation not saved." << endl;
}
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
return 0;
}
Thank you for any help! :)
Here's a way of doing it:
Create a class fruit with private variables name and cost.
Then create a constructor that takes a string (a line from the input file). Extract everything up to ':' into name and the value that follows into cost.
Your function that read file needs to do something like this:
declare an array of fruit
loop:
get a line from file into a variable
call the fruit class with this variable, and add the created object into an array
When you reach the end of the file, you have an array of fruits that contains all the data from the file.
to learn about classes, check: http://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm
to learn about reading from files, check: http://www.cplusplus.com/doc/tutorial/files/
I am having a couple problems with my code.
First off, with the code like it is, No matter what information I put in, It always returns 0, Any suggestions on where to fix this and how? I believe it has something to do with my Class Employee. How would I go about fixing this?
Second, How do I access the information in int total()? I need to access it for the last bit of code.
Also if you notice anything else that I can do to optimize my program, I welcome your suggestions. I am learning C++ as I go and will always be a Student.
// Datamax.cpp
// Created by Kennith Adkins
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public:
string eName;
float eHours;
float eWage;
float ePay;
float eOvertimeHours;
float eOvertimePay;
float eTotalPay;
float eTotalBaseHours;
float eTotalSalary;
float eTotalOvertimeHours;
int Overtime ()
{
if (eHours > 40)
{
eOvertimeHours = (eHours - 40);
eOvertimePay = (eOvertimeHours * (eWage * 1.5));
ePay = ((eHours - eOvertimeHours) * eWage);
eTotalPay = ePay + eOvertimePay;
}
else
{
ePay = (eHours * eWage);
}
}
int total()
{
eTotalBaseHours = (employee1.eHours - employee1.eOvertimeHours) + (employee2.eHours - employee2.eOvertimeHours) + (employee3.eHours - employee3.eOvertimeHours);
eTotalSalary = (employee1.eTotalPay + employee2.eTotalPay + employee3.eTotalPay);
eTotalOvertimeHours = (employee1.eOvertimeHours + employee2.eOvertimeHours + employee3.eOvertimeHours);
}
} employee1, employee2, employee3;
// Start the main program here
int main()
{
// Gretting
cout << "Welcome to the Employee Pay Center\n";
// Employee1 information
cout << "Enter the employee name: ";
cin >> employee1.eName;
cout << "Enter the hours worked: ";
cin >> employee1.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee1.eWage;
cout << endl; // Adding a blank line to space the information out
// Employee2 information
cout << "Enter the employee name: ";
cin >> employee2.eName;
cout << "Enter the hours worked: ";
cin >> employee2.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee2.eWage;
cout << endl; // Adding a blank line to space the information out
// Employee3 information
cout << "Enter the employee name: ";
cin >> employee3.eName;
cout << "Enter the hours worked: ";
cin >> employee3.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee3.eWage;
cout << endl; // Adding a blank line to space the information out
// Returning the information to the Employeer
cout << "Employe Name ............ = " << employee1.eName << "\n";
cout << "Base Pay................. = " << employee1.ePay << "\n";
cout << "Hours in Overtime........ = " << employee1.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee1.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee1.eTotalPay << "\n\n";
cout << "Employe Name ............ = " << employee2.eName << "\n";
cout << "Base Pay................. = " << employee2.ePay << "\n";
cout << "Hours in Overtime........ = " << employee2.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee2.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee2.eTotalPay << "\n\n";
cout << "Employe Name ............ = " << employee3.eName << "\n";
cout << "Base Pay................. = " << employee3.ePay << "\n";
cout << "Hours in Overtime........ = " << employee3.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee3.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee3.eTotalPay << "\n\n";
cout << "*******************************************************\n";
cout << "*****************EMPLOYEE SUMMARY DATA*****************\n";
cout << "*******************************************************\n";
cout << "** Total Employee Salaries............ " << "**\n";
cout << "** Total Employee Hours............... " << "**\n";
cout << "** Total Overtime Hours............... " << "**\n";
cout << "*******************************************************\n";
cout << "*******************************************************\n";
return 0;
}
Hey Guys, Thanks for the help. I have most of it done now. It is displaying all the information. I am now just working on getting it to display the Employee Summary Data. I revamped my code to make it cleaner because I was trying every suggestion given to me as I learn best by hands on.
That's what you get for using non-initialized variables. You have set no value to your class members, you can't expect the compiler to guess what is your employee's name or total pay.
You need to use the form:
object name.member name = value
Of course, you should call the functions before outputting results that are supposed to be produced by these functions:
employee1.Overtime();
employee2.Overtime();
employee3.Overtime();