Xcode won't recognize/read file properly - c++

I built a program in c++ to calculate the amount of gas money I owe to my dad for my summer job at Domino's. What the program does is read two lines from a file in a do while loop, one for the starting mileage that day and one for the ending mileage of that day. However I just can't get the program to read the file properly. I'm positive I opened it correctly and put it in the right spot (same folder as the .cpp file) but it just won't read it properly. Any ideas?
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
inputFile.open("sample.txt");
int days; // number of days Alisha worked
int count = 1;
int totalMileage = 0;
int addMileage;
int startMileage;
int endMileage;
double avgMileage;
double moneyOwed;
double realOwed;
const double PER_MILE = 0.08125;
cout << endl;
cout << "How many days did Alisha work?" << endl;
cin >> days;
days++;
do
{
inputFile >> startMileage;
cout << "The starting mileage for day " << count << " is " << startMileage << endl;
inputFile >> endMileage;
cout << "The ending mileage for day " << count << " is " << endMileage << endl;
addMileage = endMileage - startMileage;
totalMileage = totalMileage + addMileage;
count++;
cout << endl;
}
while (count != days);

Related

How to find positions of repeated characters in a string?

How can I find the positions of repeated characters in a string? For example, the inputted string is "11-28-1995". My goal is to assign each of those values between the "-", a variable, so I would have month = 11, day - 28, and year = 1995. This is what I have got so far, although I am not sure how to iterate after the month.
#include <iostream>
using namespace std;
int main() {
string input;
cout << "What is the date?" << endl;
cin >> input;
int pos = input.find("-");
int month = stoi(input.substr(0, pos));
cout << month << endl;
cout << day << endl;
return 0;
}
Maybe you are looking for something like this:
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <sstream>
#include <cassert>
using namespace std;
int main() {
string input;
cout << "What is the date?" << endl;
cin >> input;
unsigned int day = 0;
unsigned int month = 0;
unsigned int year = 0;
stringstream ostr(input.c_str());
char c1, c2 = 0;
ostr >> day >> c1 >> month >> c2 >> year;
assert((c1 == c2) && (c2 == '/'));
cout << "Day: " << day << endl;
cout << "Month: " << month << endl;
cout << "Year: " << year << endl;
return 0;
}
For a more general token extractor, you may be interested in the use of getline:
use getline and while loop to split a string
Hope it helps ;)

If statement inside loop not reading total right cout displaying wrong

Hello all I want to do is for last cout statement display whatever apartment has the highest rent and the apartment name. Right now it displays the total rent of all complexes enter and whatever the last complex name entered. I am stuck on this and could really use some help on this. I am new to c++ so please talk to me in layman terms it is hard for me to understand somethings.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("rentfile.txt");
int numComplex, numMonths;
double rent, totalAllRent = 0; //// Accumulator for total scores
string nameComplex;
string highNameComplex;
double averageRent;
double highestRentTotal = 0;
//set up numeric output programing
cout << fixed << showpoint << setprecision(1);
cout << "How many complexes will you enter?";
cin >> numComplex; //number of complexes enter
cout << "How many months of rent will you enter complex?";
cin >> numMonths; //number of months of rent enter
for (int complex = 1; complex <= numComplex; complex++)
{
cout << "Enter Complex Name ";
cin >> nameComplex;
outputFile << nameComplex << " ";
for (int months = 1; months <= numMonths; months++)
{
cout << "Enter Rent " << months << " for ";
cout << " Complex " << complex << ": ";
cin >> rent;
outputFile << rent << endl; //write data to output file
totalAllRent = totalAllRent + rent;
if (totalAllRent > highestRentTotal)
{
highNameComplex = nameComplex;
highestRentTotal = totalAllRent;
}
averageRent = totalAllRent / numComplex;
}
}
outputFile.close(); //close the file
ifstream inputFile;
inputFile.open("rentfile.txt");
cout << "Complex Monthly rent Collected per Complex " << endl;
while (inputFile >> nameComplex)
{
for (int i = 0; i < numMonths; i++)
{
inputFile >> rent;
cout << nameComplex << " " << rent << endl;
if (rent == 0)
cout << "Warning one of the complexes submitted zero rent for one of the months " << endl;
}
}
cout << "Total rent collected for the company = " << totalAllRent << endl;
cout << " Average Monthly rent collected for the company = " << averageRent << endl;
cout << highNameComplex << "collect the most rent = " << highestRentTotal << endl;
system("pause");
return 0;
}
Well...if it's me, I'll design the program as follows:
1. Define a vector<vector<double>> vvRents for storing the rents of all apartments by month.
2. Each element in vvRents stores the rents of all months of each apartment.
3. Once all data is collected, calculate summed rents of the year by apartment, and store the total rents in a new vector vTotalRents.
4. Use a max_element algorithm to pick the most expensive apartment.
You must include <vector> to use vector class, and include <algorithm> to use max_element.

finding the average of sums made in a loop in c++

Hello everyone I'm trying to find the average of a random amount of numbers that are input into a loop. For sum reason after the loop im able to print the right total, but when i try to find the average i get a weird answer. can anyone help me with this or direct to a thread on here that could help? I wasnt able to find anything on here.
here is my code for the program that isnt working.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inData;
string golferFile;
string golfer;
int matches;
int score;
cout << endl;
cout << "Enter the golfer's filename: ";
cin >> golferFile;
inData.open(golferFile.c_str());
getline(inData, golfer);
inData >> matches;
cout << endl;
cout << "The golfer " << golfer << " has " << matches << " matches with scores"
" of" << endl;
cout << endl;
int count;
count = 1;
int matchNumber;
matchNumber = 1;
int sum;
while(count <= matches)
{
inData >> score;
cout << "Match " << matchNumber << ": " << score << endl;
matchNumber++;
count++;
sum = sum + score;
}
}
int mean;
mean = sum / matches;
cout << "The mean score is " << mean << endl;
return 0;
}
the output i receive is this for the mean
The mean score is 1399255
I found several error in your code.
you forget to initialize your sum variable.
in while loop an extra brace found.remove it
you didn't write anything to stop your loop.that why your loop run infinite time.so initialize you loop also.

I am designing a programming that calculates the odds of profiting if you played several scratch- off lottery games

This is the code I have written so far to calculate the odds of profiting from playing lottery scratchers. I have to prompt the user for out output file name (output.txt), where a formatted table with the results will be written. So far my program will output the results, but not in an output file. I am not really sure how to do that or where that will go in my code.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Declaring variables
int lowestAmountOfProfit;
char filename[]="scratcher.txt";
string gameName;
int CostOfTicket, NumberOfPrizes;
int PrizeValue, NumberOfTickets, TicketsNotClaimed;
double RemainingTickets;
double RemainingTicketsForProfit;
double odds;
// The program will ask the user to enter the lowest amount they would like to
// profit when playing the lottery.
cout << "Enter the lowest dollar amount that you would like to profit: "
cin >> lowestAmountOfProfit;
cout << "Enter the output file name: "
cout << "Generating report..."
//open input file
ifstream fin;
fin.open(filename);
//if input file does not exist
if (!fin)
{
// If the input file cannot be found.
cout << "Input file does not exist." << endl;
return 0;
}
//How the output displace will be formatted.
cout << left << setw(25) << "Game" << setw(10) << "Cost" << setw (10) << "Odds" << endl;
cout << "-----------------------------------------------" << endl;
// Reads the name of the game
while (getline(fin, gameName))
{
fin >> CostOfTicket; // Reads the cost of ticket
fin >> NumberOfPrizes; // Reads the number of prizes
RemainingTickets = 0;
RemainingTicketsForProfit = 0;
for (int i = 0; i < NumberOfPrizes; i++)
{
fin >> PrizeValue; // Reads the prize value
fin >> NumberOfTickets; // Reads the total number of tickets
fin >> TicketsNotClaimed; // Reads number tickets not claimed
//regardless of prize value*/
// The following line computes the running sum of the number of tickets remaining for that game.
RemainingTicketsForProfit = RemainingTicketsForProfit + TicketsNotClaimed;
// The next line with compute a sum of the number of remaining tickets where the user would profit.
if (PrizeValue > lowestAmountOfProfit)
{
RemainingTickets = RemainingTickets + TicketsNotClaimed;
}
}
// Tells program what to do if there are zero remaining tickets
if (RemainingTickets==0)
{
// Formats the output
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "Not possible" << endl;
}
else
{
// Tells the program to calculate the odds
odds = RemainingTicketsForProfit / RemainingTickets;
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "1 in " << setprecision(2) << fixed << odds << endl;
}
// Read the blank line
string blankLine;
fin >> blankLine;
}
// Close the input file
fin.close();
return 0;
}
You can output to a file by just declaring it as a ofstream and then basically using it as a cout. Like so:
ofstream outputFile;
outputFile.open("filename.txt");
cout << "Enter the first number: ";
cin >> num1;
outputFile << num1 << endl;
outputFile.close();

outFile C++ not writing to output text

Down below is my incomplete program. I am having problems with writing to a text file. For example I want to write the number of snow days to a text file, but nothing shows up in the textfile when I debug in VS 2010. It does display my info and name, but nothing else works. It wont write anything after that. its NOT writing to a text file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
const string INFORMATION = "College Class";
const string MY_NAME = "Tom Hangler";
int main(void)
{
ofstream outFile;
int numberOfSnowDays;
int greatestSnowDay;
int dayNumber;
double amounttOfSnow;
outFile.open("Ex1Out.txt");
outFile << setw(51) << INFORMATION << endl << setw(48) << MY_NAME << endl;
cout << "Please enter num of days it snowed: " << endl;
cin >> numberOfSnowDays;
outFile << setw(10) << "Number of days of snow is: " << setw(10) << numberOfSnowDays;
int index;
//Problem 1 for-loop
for (index = 0; index < numberOfSnowDays; index++)
{
cout << "Enter day: " << endl;
cin >> dayNumber;
cout << "Enter amount of snow: " << endl;
cin >> amountOfSnow;
};
return 0;
}
here is what my output displays:
College Class (centered)
Tom Hangler (centered)
If i try to write anything after this, Nothing is written ever to the output file. And the output text file IS in my VS project that contains my .cpp file. I added the text file to project.
Try closing the stream at the end of the function, it looks like the data isn't getting flushed.
outFile.close();
Your code compiles and works on gcc 4.4.5 (apart from typo in amounttOfSnow).
Is it possible that you are looking at an old Ex1Out.txt file ?
Its most likely created in the Release or Debug subdirectory in your project, not where the .cpp files are.
in your for loop, you only collect the amount of snow, but you don't write it to the text file.
Do you want to do something like this?
...
for (index = 0; index < numberOfSnowDays; index++)
{
cout << "Enter day: " << endl;
cin >> dayNumber;
cout << "Enter amount of snow: " << endl;
cin >> amountOfSnow;
// next line is new:
outFile << "Day#: "<< dayNumber << ", snow: "<< amountOfSnow<<endl;
};
outFile.close()
...