C++ Text Array with User Input, then printing the input - c++

I’m hoping someone could help me out. Below is my current code. Please be gentle, this is legitimately my first program in C++, and it’s been about a year since I last touched C. And yes, this is for homework ~ I’ve used this page enough to know it’s asked quite a bit ;)
What I’m having an issue with, and struggling to find something moderately helpful regarding it, is how do I create an array to store user input text?
As you can see from the flow of the code: I ask how many items does the user want to purchase… this then dictates the looping, asking the user for the item name being purchased, the cost per item, and the total quantity. I am fine with the math part ~ I have the total items purchased and the running subtotal printing out pretty accurately. However, what I would like to do is print, in order, the names of the items that were purchased, too.
Current Code Output:
How many items do you want to enter? 3
What is the item name? Honey
What is the unit price for Honey? 5.99
How many purchased? 3
What is the item name? Milk
What is the unit price for Milk? 2.79
How many purchased? 2
What is the item name? chocolate
What is the unit price for chocolate? 1.97
How many purchased? 5
Bill Date:
Items Purchased: 10
Subtotal: 33.4
In between “Bill Date” and “Items Purchased” I would like to list, line by line, the (3) items purchased: Honey, Milk, and chocolate. It’s the storing of the item name and incrementing it that I am very much stuck on. If someone could point me in the right direction, I would greatly appreciate it. And please, the lengthier you explain the how's and why's, the better for me. Text/char arrays and I are mere acquaintances, whereas numerical int arrays and I are drinking buddies.
Thank you!! :D
Desired Code Output:
Bill Date:
Honey
Milk
chocolate
Items Purchased: 10
Subtotal: 33.4
My Code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <time.h>
using namespace std;
int main()
{
int itemCount = 0, i, itemQty;
int numOfItems = 0;
char itemName[25];
double itemCost;
double itemSub;
double subtotal = 0;
cout << "How many items do you want to enter? ";
cin >> itemCount;
for(i = 0; i < itemCount; i++)
{
cout << "What is the item name? ";
cin >> itemName;
cout << "What is the unit price for " << itemName << "? ";
cin >> itemCost;
cout << "How many purchased? ";
cin >> itemQty;
numOfItems = numOfItems + itemQty;
itemSub = itemQty * itemCost;
subtotal = subtotal + itemSub;
}
cout << "\n\tItems Purchased: " << numOfItems;
cout << "\n\tSubtotal: " << subtotal << "\n";
}

What is the largest number of items to be purhcased?...I suppose it is 100..Instead of making an array of chars you can make an array of string so change the line char itemName[25]; to string itemName[100]; then inside the for loop change the input and output of itemname to cin >> itemName[i];
cout << "What is the unit price for " << itemName[i] << "? ";
then you can output the names of items at last this way:
for(int i=0;i<itemCount;i++)
{
cout<<endl<<itemName[i];
}
cout << "\n\tItems Purchased: " << numOfItems;
cout << "\n\tSubtotal: " << subtotal << "\n";

Related

How To Find Specific Data From A Text File and Change It?

I'm new to programming and I'm trying to change this code to write it to a text file.
Basically I have to find the price of an item that was stored in the array 'List', each pointer contains an item code, description, price and discount.
I'm having two problems though, finding the item's price in the text file and than changing it by the user's input.
void DoSetItemPrice(void)
{
int `searchCode` = 0;
double changePrice = 0.00;
cout << "Enter Code For Search: ";
cin >> searchCode;
cout << endl;
cout << "Enter Price Change: $";
cin >> changePrice;
cout << endl;
for (int i = 0; i < numItems; i++)
{
if (List[i].HasCode(searchCode) == true)
{
List[i].SetPrice(changePrice);
cout << "New Price: $" << List[i].GetDiscount();
} else
cout << "The Code You Entered Could Not Be Found";
}
}
i had this kind of situation before but my solution was kinda bad but here it is anyways,i don't know any pre defined functions in C++ that helps with string manipulation, but u can try entering a character before the price like 'ù' for example ,if the price is 100$ the string would become "ù100$" then based on that u can use a loop to check the text file u are reading and when ever u encounter the character 'ù' that means what comes after it is the price so u convert that part into numbers until u reach the '$' character which indicates the end of the price.

Why int plus float shows me weird number?

I am new to c++ and I am trying to accomplish my 1st assignment. I don't need a decision but I want to know what am I doing wrong? Here is my code:
#include <iostream>
using namespace std;
int main(){
int chTenders;
int frOrders;
int macCh;
int drinks;
int sauces;
float tip;
float subtotal;
subtotal = chTenders + frOrders + macCh + drinks + sauces + tip;
cout << "How many chicken tenders would you like?\n";
cin >> chTenders;
cout << "How many orders of fries would you like?\n";
cin >> frOrders;
cout << "How many orders of mac and cheese would you like?\n";
cin >> macCh;
cout << "How many drinks would you like?\n";
cin >> drinks;
cout << "How many sauces would you like?\n";
cin >> sauces;
cout << "How much would you like to tip?\n";
cin >> tip;
cout << "====Slim's Order====\n";
cout << "Subtotal $" << subtotal << endl;
return 0;
}
And when I compile and run this it gives me $2.60929e+08 instead of 6.0:
How many chicken tenders would you like?
1
How many orders of fries would you like?
1
How many orders of mac and cheese would you like?
1
How many drinks would you like?
1
How many sauces would you like?
1
How much would you like to tip?
1
====Slim's Order====
Subtotal $2.60929e+08
I think the order of your calculations is just off. subtotal is calculated before you receive input values into the summands (chTenders, frOrders, etc.). Move the subtotal=... line to after the cin << tip statement.
To elaborate on the why, you are computing the value of subtotal before you assign any values to the variables. In C++, until you assign a value to a variable, the result of accessing it is based on what ever happened to be written to that bit of memory by some other process. So you essentially computed a garbage value and then asked the user for input. It is often considered a good practice in C++ to initialize variables at the same time they are defined.

How can I fix my source code in my C++ program called Flix for Fun Profit Report?

I have coded a program in C++ for an assignment in my C++ Intro class but I have multiple errors in the program but I can't seem to figure out how to get all of the bugs out.
The program is supposed to ask the user for the name of the movie, the number of adult and child tickets sold, and calculate the gross box office profit, net box office profit and the amount paid to the distributor.
I can't seem to figure out how to initialize the variables adultTicketPrice and
childTicketPrice and I thought I declared them and am trying to figure out if they need to get initialized if I already declared them?
And how is the childTicket price out of scope?
And why am I getting the other errors and how can I fix them?
// Michael VanZant
// Flix for Fun Profit Report
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Create all double variables
double adultTicketsSold, childTicketsSold, grossBoxProfit, netBoxProfit,
amtPaidDist, adultTicketPrice, childTicketPrice
adultTicketPrice = 12;
childTicketPrice = 7;
cout << fixed << setprecision(2);
// Create the string variable
string movieName;
// Get the name of the movie and store it in the movieName string
cout << "What is the name of the movie?";
getline(cin, movieName);
cout << "\n";
// Cin.ignore to ignore the string variable type
cin.ignore();
// Get the amount of adult and child tickets sold
cout << "How many adult tickets do you want to buy?";
cin >> adultTicketsSold;
cout << "\n";
cout >> "How many child tickets did you want to buy?";
cin >> childTicketsSold;
cout << "\n";
// Calculate the amount of gross box office profit and display it
grossBoxProfit = (childTicketsSold * childTicketPrice) + (adultTicketsSold * adultTicketPrice);
cout << "Gross Box Office Profit: $" << grossBoxProfit;
cout << "\n";
// Calculate the net box profit amount and display it
netBoxProfit = grossBoxProfit * .20;
cout << "Net Box Profit Amount: $" << netBoxProfit;
cout << "\n";
// Calculate the amount paid to distributor and display it
amtPaidDist = grossBoxProfit - netBoxProfit;
cout << "Amount Paid to Distributor is: $" << amtPaidDist;
return 0;
}
When the compiler says "expected initialiser", it has nothing to do with these lines:
adultTicketPrice = 12;
childTicketPrice = 7;
which are actually assignments, not initialisations (though some old C terminology would call the first assignment an initialisation).
No, it's because it thinks you're still on this line, providing declarations and (optionally) initialisers:
double adultTicketsSold, childTicketsSold, grossBoxProfit, netBoxProfit,
amtPaidDist, adultTicketPrice, childTicketPrice
That's because you didn't put a ; at the end of it.
Also:
cout >> "How many child tickets did you want to buy?";
You meant <<.
Fixing those two little typos, the code compiles.

Error saying, "statement cannot resolve address of overloaded function"

I'm a beginner programmer, so this is going to look messy, but I keep getting the problem that is mentioned in the title. No matter where I try to put endl; it keeps giving me the same error. Also when I run the code my total for the second store comes out right but the first store total does not. Any idea on how to fix this? I'm using codeblocks on a windows 7 computer.
#include <iostream> //Allows cout/cin
#include <ctime> //Allows time
#include <iomanip> //Allows setprecision
using namespace std;
int main()
{
//Include header
//Input variables
double widgetStores;
double numberSoldFirst1;
double numberSoldFirst2;
double numberSoldSecond1;
double numberSoldSecond2;
double widgetsLeftS1W2;
double widgetsLeftS2W1;
double widgetsLeftS2W2;
//Start Clock
clock_t begin, end;
double time_spent;
begin = clock();
//Prompt for total number in stores
cout << "Total number of widgets at each store starting with :";
cin >> widgetStores;
double widgetStore1=widgetStores;
double widgetStore2=widgetStores;
double widgetsLeftS1W1;
//Prompt for amount sold during first and second week
cout << "How many widgets were sold at Store 1 the first week? ";
cin >> numberSoldFirst1;
cout << "How many widgets were sold at Store 1 the 2nd week? ";
cin >> numberSoldSecond1;
cout << "How many widgets were sold at Store 2 the first week? ";
cin >> numberSoldFirst2;
cout << "How many widgets were sold at Store 2 the 2nd week? ";
cin >> numberSoldSecond2;
//Calculate Number of widgets
widgetsLeftS1W1-=(widgetStore1-numberSoldFirst1);
widgetsLeftS1W2-=(numberSoldFirst1-numberSoldSecond1);
widgetsLeftS2W1-=(widgetStore2-numberSoldFirst2);
widgetsLeftS2W2-=(numberSoldFirst2-numberSoldSecond2);
//Display Values
cout << "Store 1 has " << widgetsLeftS1W2 << " widgets left after the 2nd week.";
cout << "Store 2 has " <<widgetsLeftS2W2 << " widgets left after the 2nd week.";
//Show time elapsed
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
cout << setprecision(2) << fixed << "****Elapsed time:" <<time_spent/60 << "minutes****";
return 0;
Did you try something like
cout << "Total number of widgets at each store starting with :";
cin >> widgetStores;
cout << endl; //Added this
cin doesn't have a << operator, so you need to send it to cout.
Edit: I found the error you're having. I guess that you are trying to put in lines as literally
endl;
and that doesn't go anywhere...
The only compile error this program has, is that you're using widgetsLeftS1W1, widgetsLeftS1W2, widgetsLeftS2W1 and widgetsLeftS2W2 before initializing them.
You probably need = instead of -=.
When you say
widgetsLeftS1W1 -= (widgetStore1-numberSoldFirst1);
what you actually mean is
widgetsLeftS1W1 = widgetsLeftS1W1 - (widgetStore1-numberSoldFirst1);
The computer doesn't know the value of widgetsLeftS1W1, so it gives you the error.
Conclusion: use
widgetsLeftS1W1 = (widgetStore1 - numberSoldFirst1);
Try initializing the values of
widgetsLeftS1W1
widgetsLeftS1W2
widgetsLeftS2W1
widgetsLeftS2W2
with zero while declaring them at the top.

C++ file input/output and array assistance

I have a C++ project to do for my class and it's quite intricate, to me at least. I've got the general idea and concept down, but i'm running into some other problems when it comes to the arrays and file stuff. Below is what the project consists of
You will be building and modifying a class roster system for a Teacher to manage his class roster and their final grades. This program
will use functions for the various menu options, and you will work with
the data in arrays or vectors. The program will provide a menu system that allows for the teacher to perform tasks until he chooses to close the program. The program will read and write to a file called
classroster.txt. Any and all additions, deletions, or changes to the roster will be saved in classroster.txt file.
This file will contain the names of each of the students in the class with their grade. See the following for an example listed below of how the data would be stored in the classroster.txt file. You should work with the data using arrays or vectors.
Jim Jones C
Kevin James B
Marc Cohen A+
When the program starts it should read the data from the classroster.txt into arrays or vectors. While the program is running it should use the arrays or vectors for the functions while using the program. When the program ends it should overwrite the classroster.txt file if something has been changed. The
programs menu will offer the following options and will allow the user to keep performing functions until they choose to exit the program ( hint !!!!! you will need to use a loop for the menu system)
Add A New Student-
This will allow the user to add a new student to the system. The system should prompt for the new students full name and then grade.
It should validate that the grade is in the following values
(A+, A, A-, B+, B, B-,C+,C, C-, D+, D, D-, F) and if not
in the approved list it should prompt the user for a valid grade.
Change a Students Grade-
This will find the student in question and change the grade. If the specified student doesn’t exist the program should print an error message telling the user that you couldn’t find the specified student to
change their grade.
Remove a Student-
Will remove a student and their grade from the roster. If the specified student doesn’t exist the program should print an error message telling the user that you couldn’t find the specified student to remove.
Display Class Roster–
(Bonus Points if you can display the names is alphabetical order) This
function will display the list of all the students and their grades on
the screen that looks like this:
Student Name Grade
Jim Jones C
Kevin James B-
Marc Cohen A+
This is what i have so far, it's obviously not done yet
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
const int num_of_students;
const int new_student = 1, change_grade = 2, remove_student = 3, display_roster = 4, quit = 5;
int classroster[num_of_students];
int student_grade[num_of_students];
string possible_grades[13] = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"};
int choice;
ofstream class_file;
cout << "How many students do you have in your class?" << endl;
cin >> num_of_students;
cout << "---MENU---" << endl;
cout << "1. Add A New Student" << endl;
cout << "2. Change A Students Grade" << endl;
cout << "3. Remove A Student" << endl;
cout << "4. Display Class Roster" << endl;
cout << "5. Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == new_student) {
for (int index = 0; index < num_of_students; index++) {
class_file.open("classroster.txt");
cout << "What is the name of the student you want to add? ";
getline(cin, classroster);
if (student_grade == possible_grades) {
cout << "What is the final grade of this student? ";
getline(cin, student_grade);
}
else {
"Please enter a valid grade!"
}
cout << "Student added!";
}
}
else if (choice == change_grade) {
class_file.open("classroster.txt");
cout << "What is the name of the student whose grade you want to change? ";
getline(cin, )
}
else if (choice == remove_student) {
}
else if (choice == display_roster) {
}
else if (choice == quit) {
}
else {
cout << "Please enter a valid choice!"
}
system("PAUSE");
return 0;
}
First, to answer your question, here's one way to search an array of student names:
int index = -1;
for(int k=0; k<num_of_students; ++k)
{
if(names[k] == name)
index = k;
}
And here's a way to change the array of grades:
student_grade[index] = 3;
More generally, you taking the wrong approach. Your code does not compile, so it looks as if you're writing it all out before testing any of it. As they never seem to teach in school, you should start with something small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work.
Let's start with the number of students:
int main() {
const int num_of_students;
cout << "How many students do you have in your class?" << endl;
cin >> num_of_students;
return(0);
}
Try to compile this, and you'll find that there's something wrong. Fix it and try constructing an array of int and filling it in. Once that's working, try an array of string. Small steps.
You realy should be using maps for this question, its makes the most sense. Here is code to read in the map from a file. After you have the map all the operations you need are already implemented in the STL. I realize you may need to use vector but I'd like to think you wouldn't be penalized for being clever and actually writing a proper solution.
#include <map>
#include <fstream>
#include <iostream>
using namespace std;
int main(){
map<string,string> data;
fstream fs("classroster.txt");
while(fs.good()){
string fname, lname, grade;
fs >> fname;
fs >> lname
fs >> grade;
fname += lname; //Concat Names to get full
if(grade == "A") //Check other grades as well.
data.emplace(fname,grade);
}
while(1){
string option;
std::cout << "Options:" << endl;
cin >> option;
//Your option selection code here
}
return 0;
}
EDIT:
maps are also sorted by key name so printing alphabetically is very easy, no sorting required.
for(auto& pairs : data)
cout << pairs.first << " " << pairs.second << endl;