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/
Related
its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.
So I'm writing a basic application and for some reason when I run the program a bunch of numbers pop up before my intended output. It was working fine until I added the "std::cout" lines to have the outputs only be 2 decimals. The general gist of the application is a program acts as a self-checkout register at a store and lets the user buy 2 items. And yes I know the code probably looks really bad, I'm still super new to C++.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float price1;
float number1;
float price2;
float number2;
float priceofitemplustax1;
float priceofitemplustax2;
float total;
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << price1;
std::cout << price2;
std::cout << priceofitemplustax1;
std::cout << priceofitemplustax2;
std::cout << total;
cout << endl << "Please scan your first item." <<endl;
cin.get();
cout << endl << "How many of that item are you buying? "<<endl;
cin >> number1;
cout << endl << "How much is that item?"<<endl;
cin >> price1;
priceofitemplustax1 = (number1 * price1) * 1.0875;
cout << endl << "So you want " << number1 << " of this item? Adding tax that will be " << priceofitemplustax1 << "."<<endl;
cin.get();
cout << endl << "Please scan your second item."<<endl;
cin.get();
cout << endl << "How many of that item are you buying? "<<endl;
cin >> number2;
cout << endl << "How much is that item?"<<endl;
cin >> price2;
priceofitemplustax2 = (number2 * price2) * 1.0875;
cout << endl << "So you want " << number2 << " of this item? Adding tax that will be " << priceofitemplustax2 << "."<<endl;
cin.get();
total = priceofitemplustax1 + priceofitemplustax2;
cout << endl << "So your final total for this shopping trip including tax is " << total << "."<<endl;
cin.get();
cout << endl << "Your reciept will print below."<<endl;
cin.get();
cout << setw(14) << right << "Number of Item" << setw(10) << right << "Price" << setw(20) << "Price plus tax" << endl;
cout << setw(14) << right << number1 << setw(10) << right << price1 << setw(20) << priceofitemplustax1 << endl;
cout << setw(14) << right << number2 << setw(10) << right << price2 << setw(20) << priceofitemplustax2 << endl;
cout << endl;
cout << endl;
cout << setw(8) << right << "Total is" << setw(10) << total << price2 << endl;
cin.get();
}
std::cout << std::setprecision(2);
std::cout << price1;
std::cout << price2;
std::cout << priceofitemplustax1;
std::cout << priceofitemplustax2; std::cout << total;
here you write 5 floats
The lines
std::cout << std::fixed; // sets a format
std::cout << std::setprecision(2); // sets a format
set the streams output format.
The lines
std::cout << price1; // outputs a number
std::cout << price2; // outputs a number
std::cout << priceofitemplustax1; // outputs a number
std::cout << priceofitemplustax2; // outputs a number
std::cout << total; // outputs a number
print the variables to the stream.
Just remove the variable output lines. Do not accept this answer - Credit goes to manni66
I was able to loop a file that gave me the miles driven, gallons used, and gasoline cost at a certain day successfully. Now I'm trying to figure out how to get the sum of miles driven, gallons used, and gasoline cost by using loops
int main()
{
ifstream inputFile;
int x = 1;
int milesDriven = 0;
double gallonsUsed = 0,
gasolineCost = 0;
int truckNumber,
numberOfTrips,
sumMilesDriven = 0;
double sumGallonsUsed = 0,
sumGasolineCost = 0;
int avgMilesDriven;
double avgGallonsUsed,
avgGasolineCost;
/* Display Truck Information
Get Number of Trips
Get Truck Information
Process Each Trip
Display Averages
*/
inputFile.open("100.txt");
//Display Truck Information
cout << " " << setw(35) << "Red-Rig Trucking" << endl << endl;
cout << " " << setw(40) << "Summary of Truck Operations" << endl << endl;
inputFile >> truckNumber;
cout << "Truck: " << truckNumber << endl << endl;
inputFile.close( );
inputFile.open("truck.txt");
//Get Number of Trips
inputFile >> numberOfTrips;
//Get Truck Information
cout << "Day" << " " <<setw(16) << "Miles" << " " << setw(16) << "Gallons"
<< " " << setw(16) << "Gasoline" << endl << setw(20) << "Driven" << " "
<< setw(16) << "Used" << " " << setw(16) << "Cost" << endl << endl;
while(!inputFile.eof()){
inputFile >> milesDriven >> gallonsUsed >> gasolineCost;
cout << x << " " << setw(17) << milesDriven << " " << setw(17)
<< fixed << setprecision(2) << gallonsUsed << " " << setw(12) << fixed
<< setprecision << gasolineCost << endl ;
x++;
}
//Process Each Trip
/*while(inputFile)
{ sumMilesDriven = sumMilesDriven + milesDriven;
inputFile >> milesDriven;
}*/
for (; milesDriven--;)
sumMilesDriven += milesDriven;
cout << endl << "Sum" << " " << setw(15) << sumMilesDriven ;
for (;gallonsUsed;)
sumGallonsUsed += gallonsUsed;
cout << " " << setw(17) << sumGallonsUsed;
for (;gasolineCost--;)
sumGasolineCost += gasolineCost;
inputFile.close( );
return 0;
}
I've gotten this far and I can't figure out what's wrong. I've taken out the milesDriven >=10 from the for loop parenthesis. When the code runs I get an incorrect sum amount. The sum is either too big or too small.
Your code:
for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);{
cout << " " << setw(17) << sumGasolineCost;
}
My first advice is, do not write confusing code. Whenever you're programming, you have better things to do than tie your shoelaces together. I think you know the above is equivalent to:
for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);
cout << " " << setw(17) << sumGasolineCost;
That lets us discuss the loop itself. Go back and consult your textbook. The for loop has three components:
for( init ; test ; incr )
init is executed once, usually to initialize what will be tested
test is executed on each iteration, including the first, to determine if the loop body will be executed
incr is executed after the loop body, usually to update the tested value
In your case, sumGasolineCost += gasolineCost is in init. It is executed once. It should be in the loop body. There are other errors, too. I can't be much more specific because you don't indicate where the array or input is that you're looping over.
Once you get your loop doing what it should, you might find the standard std::accumulate function interesting to compare to.
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
}
I am trying to use setw to clean up the output of my program. I want the empty spaces in between "total number of spools to be ordered" and the output.
EDIT this is what im going for:
and this is what I get
here is what I have so far:
UPDATED CODE
/********************************************/
// Name: results /
// Description: Print results /
// Parameters: N/A /
// Reture Value: N/A /
/********************************************/
void results(int spoolnumber, int subtotalspool, float shippingcost, float totalcost)
{
cout << left << setw (45) << "Total number of spools to be ordered is: " << right << spoolnumber << endl << endl;
cout << left << setw (45) << "The subtotal for the spools is:" << right << "$" << subtotalspool << endl << endl;
cout << "The shipping cost is: $" << shippingcost << endl << endl;
cout << "The total cost is: $" << totalcost << endl << endl;
return;
}
You can also do
cout << left << setw (45) << "Total number of spools to be ordered is: " << spoolnumber << endl << endl;
to choose which side the padding goes. The default is left.
EDIT: using stringstream
stringstream ss;
ss << "$" << spoolnumber
I think you can fix the right end by adding another setw. So:
cout << left << setw (45) << "Total number of spools to be ordered is: " << right << setw(5) << ss.str() << endl << endl;