C++ Sentinel/Count Controlled Loop beginning programming - c++

Hello all this is my first post. I'm working on a homework assignment with the following parameters.
Piecework Workers are paid by the piece. Often worker who produce a
greater quantity of output are paid at a higher rate.
1 - 199 pieces completed $0.50 each
200 - 399 $0.55 each (for all pieces)
400 - 599 $0.60 each
600 or more $0.65 each
Input: For each worker, input the name and number of pieces completed.
Name Pieces
Johnny Begood 265
Sally Great 650
Sam Klutz 177
Pete Precise 400
Fannie Fantastic 399
Morrie Mellow 200
Output: Print an appropriate title and column headings. There should
be one detail line for each worker, which shows the name, number of
pieces, and the amount earned. Compute and print totals of the number
of pieces and the dollar amount earned.
Processing: For each person, compute the pay earned by multiplying the
number of pieces by the appropriate price. Accumulate the total
number of pieces and the total dollar amount paid.
Sample Program Output:
Piecework Weekly Report
Name Pieces Pay
Johnny Begood 265 145.75
Sally Great 650 422.50
Sam Klutz 177 88.5
Pete Precise 400 240.00
Fannie Fantastic 399 219.45
Morrie Mellow 200 110.00
Totals 2091 1226.20
You are required to code, compile, link, and run a sentinel-controlled
loop program that transforms the input to the output specifications as
shown in the above attachment. The input items should be entered into
a text file named piecework1.dat and the ouput file stored in
piecework1.out . The program filename is piecework1.cpp. Copies of
these three files should be e-mailed to me in their original form.
Read the name using a single variable as opposed to two different
variables. To accomplish this, you must use the getline(stream,
variable) function as discussed in class, except that you will replace
the cin with your textfile stream variable name. Do not forget to code
the compiler directive #include < string > at the top of your program
to acknowledge the utilization of the string variable, name . Your
nested if-else statement, accumulators, count-controlled loop, should
be properly designed to process the data correctly.
The code below will run, but does not produce any output. I think it needs something around line 57 like a count control to stop the loop.
something like (and this is just an example....which is why it is not in the code.)
count = 1;
while (count <=4)
Can someone review the code and tell me what kind of count I need to introduce, and if there are any other changes that need to be made.
Thanks.
//COS 502-90
//November 2, 2012
//This program uses a sentinel-controlled loop that transforms input to output.
#include <iostream>
#include <fstream>
#include <iomanip> //output formatting
#include <string> //string variables
using namespace std;
int main()
{
double pieces; //number of pieces made
double rate; //amout paid per amount produced
double pay; //amount earned
string name; //name of worker
ifstream inFile;
ofstream outFile;
//***********input statements****************************
inFile.open("Piecework1.txt"); //opens the input text file
outFile.open("piecework1.out"); //opens the output text file
outFile << setprecision(2) << showpoint;
outFile << name << setw(6) << "Pieces" << setw(12) << "Pay" << endl;
outFile << "_____" << setw(6) << "_____" << setw(12) << "_____" << endl;
getline(inFile, name, '*'); //priming read
inFile >> pieces >> pay >> rate; // ,,
while (name != "End of File") //while condition test
{ //begining of loop
pay = pieces * rate;
getline(inFile, name, '*'); //get next name
inFile >> pieces; //get next pieces
} //end of loop
inFile.close();
outFile.close();
return 0;
}

Can someone review the code and tell me what kind of count I need to introduce, and if there are any other changes that need to be made.
You need statements that direct output to your output file, just as the assignment said to do. The compiler can't read your mind, and it can't read your homework assignment either. It can only read your code.
You also have a problem with your input statements. The pay rates are not in the input file. All that's in the input file are the workers' names and the number of pieces they produced.

Related

How to split strings and pass them to class vectors from file

For my university class in programming we have been working on Object Oriented Programming (OOP) and are currently working on a group project. The project is to create a cash register that holds items with their names, amounts, and prices. As well as have a way to track the coins given by the user then determine the coin denomination. These are supposed to be done in different classes and involve objects.
My question is regarding the inventory manager that I am coding. The inventory manager is supposed to take the "data.txt" file and read it into the appropriate vectors. Currently I have a vector for the item name, price, amount, and then the itemList vector which holds a string of all 3 to print to the user for readability.
Here is a snippet from the data file:
20 1.99 Potato Chips
10 5.99 Ibuprofen
4 1.42 Candy
55 3.10 Coffee
12 3.25 Hummus
12 4.55 Guacamole
7 0.80 Baklava
45 1.50 Chocolate Chip Cookies
My question is, how do I split the line up so that I can pass the amount (first number) to the appropriate vector, pass the price to the appropriate vector, then pass the name to the appropriate vector. Essentially splitting each line into 3 parts. The part that is the most difficult to me is how the names of the items can be 1 word, 2 words, or even 3 words. Making it difficult to predict how many spaces the name will have, which caused a lot of my attempts to not work.
I found a working solution though I'm worried it's incorrect or inefficient and I'm curious in knowing the best way to do this. Thank you so much ahead of time and I will post the class definition and the method I'm working in down below.
< The stream object is inFile>
class inventoryManager
{
private:
double total, change, choice;
vector <int> amount;
vector <string> name;
vector <double> price;
vector <string> itemList;
public:
void fileOpen(fstream& inFile);
void fillInventory(fstream& inFile);
void printInventory(fstream& inFile);
};
void inventoryManager::fillInventory(fstream& inFile)
{
string temp;
string a, b;
while (!inFile.eof())
{
inFile >> a >> b;
amount.push_back(stoi(a));
price.push_back(stod(b));
getline(inFile, temp);
name.push_back(temp);
itemList.push_back(temp);
}
}
Attempted: I tried using the find() function to find each space then use the index to print the estimated indices to each side of the white space to the vectors. Though it was extremely messy and wouldn't work if a different data file was inputted. The idea of the program is to be able to work if a different file is put in, similar format but the amount could be 100, and prices could be more digits. I also tried editing the file directly by adding new lines for each space but ran into the item names with multiple spaces and ultimately didn't work.
You are trying to do too many new things at once. Break the problem into pieces and solve them separately, then combine them. To break the string into pieces you can use find and substr, you just have to be careful and debug until you're sure it's working perfectly:
string s = "45 1.50 Chocolate Chip Cookies";
cout << "s: " << s << endl; // for debugging
size_t first = s.find(' ');
cout << first << endl; // for debugging
string amountString = s.substr(0, first);
cout << amountString << "X" << endl; // for debugging
size_t second = s.find(' ', first+1);
cout << second << endl; // for debugging
string priceString = s.substr(first+1,second-first-1);
cout << priceString << "X" << endl; // for debugging
string nameString = s.substr(second+1);
cout << nameString << "X" << endl; // for debugging
The purpose of those X's is to be certain that the substring has no trailing space.
Once you have tackled the problem this way (and handed the result in for a grade), you can advance to tools like stringstream, and you won't have to deal with this grubby index arithmetic any more.

cash reg loading individual words from each line into the different struct members

I have this homework assignment that has me a little lost. I have been working on this assignment writing my code, erasing, rewrite, repeat etc. Here are the instructions:
Step (1)
Associated with this assignment is a data file called prices.txt. It contains details of the prices for items in a
grocery store. The first column is the barcode for the item (http://en.wikipedia.org/wiki/Barcode) the
second column, starting in position 11, is the product name, and the third column, starting in position 37 is
the product price.
Write a function with the signature int loadData() which prompts the user for the location of the data file
on disk and then loads the data from the file into an array of elements. Each element of the array should be
a struct declared as follows:
struct Item {
string code;
string name;
double price;
};
The array itself should be called items and should be declared at file scope as follows:
const int MAX_ITEMS = 100;
Item items[MAX_ITEMS];
Notice that the array has size 100, so you can assume the number of items in the data file is less than 100.
Therefore, when loadData has finished loading the data into the array some elements in the array will be unused. The function loadData returns the number of items actually loaded into the array.
I am unsure on how to attempt the function described in the instructions. My code:
int loadData () {
string inputFileName;
ifstream inputFile;
int numOfItems = 0;
cout << "Please input the name of the backup file: ";
cin >> inputFileName; //read user input for the location of the
//backup file
inputFile.open(inputFileName.c_str()); //open specified document
if (!inputFile.is_open()) { //If the file does not open the errormsg
cout << "Unable to open input file." << endl;
cout << "Press enter to continue...";
getline(cin, reply);
exit(1);
}
//Not sure where to start. I know I need to get each element from
//each newline.
return numOfItems;
}
I wanted to figure this out on my own but that isn't gonna happen. So if I could just get some hints or even suggested pools of knowledge that would guide me or even give me an idea of where to start.
addition: input file:
10001 Apples (bunch) 4.59
10002 Bananas (bunch) 4.99
10003 Pears (bunch) 5.49
20001 White bread (loaf) 2.69
20002 Brown bread (loaf) 2.89
20003 English Muffins (bag) 3.99
30001 Sugar (5 lb bag) 3.99
30002 Tea (box) 4.29
30003 Folger's Coffee (Can) 13.29
This is the entire input file.
Since the input file seems to be using fixed-width columns, it's actually very easy to extract the fields. Just read one line at a time, and for each line get each element as a sub-string, and put into the structure members. And there are functions to convert strings to floating-point values as well.
Don't worry about the possible leading or trailing spaces, there are ways of trimming that.

C++ reading certain lines from output file

I am making a program for class that needs to read certain lines from an output file based on what "data set" a person chooses. For example, if a person inputs "1" for the desired data set, I need it to use lines 1 through 8 of the data file (inclusively). If they input "2" for the desired data set, I need the program to use lines 9 through 16 from the data file (inclusively), and if "3", then lines 17 through 24 (inclusively).
Here is the code I have so far-
int main()
{
int latA, latB, latC, latD;
int longA, longB, longC, longD;
int AtoB, BtoC, CtoD, threeFlightTotal, nonStop;
int dataSet;
string cityA, cityB, cityC, cityD;
intro();
cout << "Which data set do you wish to use? 1, 2, or 3? ";
cin >> dataSet;
while(dataSet < 1 || dataSet > 3)
{
cout << "Sorry, that is not a valid choice. Please choose again." << endl;
cin >> dataSet;
}
ifstream dataIn;
dataIn.open("cities.txt");
if (dataIn.fail())
{
cout << "File does not exist " << endl;
system("pause");
exit(1);
}
else
{
cout << "File opened successfully" << endl;
}
dataIn.close();
system("pause");
return 0;
}
Here is my data file-
43.65 79.4
Toronto
40.75 74
New York
33.64 84.43
Atlanta
51.5 0
London
37.78 122.42
San Francisco
47.61 122.33
Seattle
44.88 93.22
Minneapolis
41.88 87.63
Chicago
21.19 157.5
Honolulu
45.31 122.41
Portland
42.2 83.03
Detroit
25.47 80.13
Miami
How would I go about doing this? I've looked at other posts but I am having a hard time understanding how to implement their solutions to mine. Thank you for any help in advance. If I'm not giving enough information let me know.
You can simply skip the unneeded lines:
//here you calculate the amount of lines to skip.
//if dataSet=1 --> linesToSkip=0, if dataSet=2 --> linesToSkip=8...
int linesToSkipt = (dataSet-1) * 8;
//getline Needs a string to load the Content.
//So we don't use the data but wee Need to store it somewhere
std::string helper;
//We use a for Loop to skip the desired amount of lines
for(int i = 0; i < linesToSkip; ++i)
std::getline(dataIn, helper); //Skip the unneeded lines
If you knew the exact length of one line you could simply seek to desired Position. But from your example data set it seems like you don't. So you Need to read the file line by line until you reach the desired Position.

C++ - How to display colon delimited text file in orderly manner?

I'm completely new to C++, so please give me a change to learn!
Assuming I have a text file RoomDB.txt which stores data in the following format :
005:Room 1:Level 1:3-Jul-14:0900:3:Mathematics 101:Julia Lee
006:Room 2:Level 2:2-Jun-14:0800:2:English 101:Jared Loo
007:Room 3:Level 3:15-Apr-14:1800:3:Chinese 101:David Tay
008:Room 4:Level 4:15-Apr-14:1200:3:Science 101:Michelle Choo
How would I selectively display a particular line (or more) of data based on the fourth field (the date), such that it would look like this - (If i want to display only the lines in which the date is 15-Apr-14)
Booking ID Room No. Level No. Time Duration Subject Lecturer
----------------------------------------------------------------------------------------
007 Room 3 Level 3 1800 3 Chinese 101 David Tay
008 Room 4 Level 4 1200 3 Science 101 Michelle Choo
PS : Notice that the date is excluded from the desired output as it will be used as a criteria for choosing what data is to be displayed. My current code is as follows :
int main()
{
cout << "\nBooking ID Room No. Level No. Time Duration Subject Lecturer" << endl;
cout << "-------------------------------------------------------------------------------" << endl;
string array[50]; // creates array to hold names
short loop=0; //short for loop for input
string line; //this will contain the data read from the file
ifstream myfile ("RoomDB.txt"); //opening the file.
if (myfile.is_open()) //if the file is open
{
while (! myfile.eof() ) //while the end of file is NOT reached
{
getline (myfile,line); //get one line from the file
array[loop] = line;
cout << "At element " << loop << ", value is :" << array[loop] << endl;
loop++;
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output
}
This is a CSV like file with delimiter :, you could:
-read the file line by line using std::getline
-spliting the line by : using Boost String Algorithm.
-loading in a structure or collection for processing.
-output necessary info

read in values and store in list in c++

i have a text file with data like the following:
name
weight
groupcode
name
weight
groupcode
name
weight
groupcode
now i want write the data of all persons into a output file till the maximum weight of 10000 kg is reached.
currently i have this:
void loadData(){
ifstream readFile( "inFile.txt" );
if( !readFile.is_open() )
{
cout << "Cannot open file" << endl;
}
else
{
cout << "Open file" << endl;
}
char row[30]; // max length of a value
while(readFile.getline (row, 50))
{
cout << row << endl;
// how can i store the data into a list and also calculating the total weight?
}
readFile.close();
}
i work with visual studio 2010 professional!
because i am a c++ beginner there could be is a better way! i am open for any idea's and suggestions
thanks in advance!
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits>
struct entry
{
entry()
: weight()
{ }
std::string name;
int weight; // kg
std::string group_code;
};
// content of data.txt
// (without leading space)
//
// John
// 80
// Wrestler
//
// Joe
// 75
// Cowboy
int main()
{
std::ifstream stream("data.txt");
if (stream)
{
std::vector<entry> entries;
const int limit_total_weight = 10000; // kg
int total_weight = 0; // kg
entry current;
while (std::getline(stream, current.name) &&
stream >> current.weight &&
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n') && // skip the rest of the line containing the weight
std::getline(stream, current.group_code))
{
entries.push_back(current);
total_weight += current.weight;
if (total_weight > limit_total_weight)
{
break;
}
// ignore empty line
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
else
{
std::cerr << "could not open the file" << std::endl;
}
}
Edit: Since you wannt to write the entries to a file, just stream out the entries instead of storing them in the vector. And of course you could overload the operator >> and operator << for the entry type.
Well here's a clue. Do you see the mismatch between your code and your problem description? In your problem description you have the data in groups of four lines, name, weight, groupcode, and a blank line. But in your code you only read one line each time round your loop, you should read four lines each time round your loop. So something like this
char name[30];
char weight[30];
char groupcode[30];
char blank[30];
while (readFile.getline (name, 30) &&
readFile.getline (weight, 30) &&
readFile.getline (groupcode, 30) &&
readFile.getline (blank, 30))
{
// now do something with name, weight and groupcode
}
Not perfect by a long way, but hopefully will get you started on the right track. Remember the structure of your code should match the structure of your problem description.
Have two file pointers, try reading input file and keep writing to o/p file. Meanwhile have a counter and keep incrementing with weight. When weight >= 10k, break the loop. By then you will have required data in o/p file.
Use this link for list of I/O APIs:
http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx
If you want to struggle through things to build a working program on your own, read this. If you'd rather learn by example and study a strong example of C++ input/output, I'd definitely suggest poring over Simon's code.
First things first: You created a row buffer with 30 characters when you wrote, "char row[30];"
In the next line, you should change the readFile.getline(row, 50) call to readFile.getline(row, 30). Otherwise, it will try to read in 50 characters, and if someone has a name longer than 30, the memory past the buffer will become corrupted. So, that's a no-no. ;)
If you want to learn C++, I would strongly suggest that you use the standard library for I/O rather than the Microsoft-specific libraries that rplusg suggested. You're on the right track with ifstream and getline. If you want to learn pure C++, Simon has the right idea in his comment about switching out the character array for an std::string.
Anyway, john gave good advice about structuring your program around the problem description. As he said, you will want to read four lines with every iteration of the loop. When you read the weight line, you will want to find a way to get numerical output from it (if you're sticking with the character array, try http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/, or try http://www.cplusplus.com/reference/clibrary/cstdlib/atof/ for non-whole numbers). Then you can add that to a running weight total. Each iteration, output data to a file as required, and once your weight total >= 10000, that's when you know to break out of the loop.
However, you might not want to use getline inside of your while condition at all: Since you have to use getline four times each loop iteration, you would either have to use something similar to Simon's code or store your results in four separate buffers if you did it that way (otherwise, you won't have time to read the weight and print out the line before the next line is read in!).
Instead, you can also structure the loop to be while(total <= 10000) or something similar. In that case, you can use four sets of if(readFile.getline(row, 30)) inside of the loop, and you'll be able to read in the weight and print things out in between each set. The loop will end automatically after the iteration that pushes the total weight over 10000...but you should also break out of it if you reach the end of the file, or you'll be stuck in a loop for all eternity. :p
Good luck!