I'm trying to be able to call the vendingmachine function and have it give me a table of the stuff i got from the file but it gives me crazy numbers like -858993460. I have to be able to change the individual amounts and prices before calling the function so it can give me different numbers.
Cola
0.75 20
Ruby Red Blast
1.00 10
Lemon Fizz
0.75 8
Grape Soda
0.90 5
Citrus Flip
0.85 0
Habanero Surprise
0.80 11
^^This is the text file im working with
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct soda{
string name;
double price;
int amount;
};
void vendingmachine(struct soda[6]);
int main(){
ifstream inFile;
soda soda[6];
inFile.open ("machine.txt");
if ( inFile.fail() )
{
cout << "Error: Data file could not be opened" << endl;
exit (EXIT_FAILURE);
}
for(int i=0; i < 6; i++){
getline(inFile, soda[i].name);
inFile >> soda[i].price;
inFile >> soda[i].amount;
inFile.ignore(100,'\n');
}
cout << "Welcome to the vending machine!" << endl;
cout << endl;
vendingmachine(soda);
return 0;
}
void vendingmachine(struct soda soda[6]){
cout << "***************************************************************" << endl;
cout << " " << "Drink Name" << " " << "Price Per Can" << " " << "Number in Machine" << endl;
for( int i=0; i < 6; i++){
cout << setw(17) << soda[i].name << setw(16) << soda[i].price << setw(20) << soda[i].amount << endl;
}
cout << "***************************************************************" << endl;
}
Thanks everyone, i changed it to how it should be.
You are declaring a local variable soda and operating on that in the function
void vendingmachine(struct soda[6]){
soda soda[6];
You need to operate on the caller's array instead
void vendingmachine(struct soda soda[6]){
//soda soda[6];
Change your function to this:
void vendingmachine(struct soda soda[6]){
cout << "***************************************************************" << endl;
cout << " " << "Drink Name" << " " << "Price Per Can" << " " << "Number in Machine" << endl;
for( int i=0; i < 6; i++){
cout << setw(17) << soda[i].name << setw(16) << soda[i].price << setw(20) << soda[i].amount << endl;
}
cout << "***************************************************************" << endl;
}
THEN!
Go to your loop where you are receiving the data from the text file and type this:
cout << soda[i].name << endl;
(now run the program)
You will notice that the whole first line is attributed to the Cola then there are 5 blank lines that are printed.
Now all you need to do is make sure the variables from the text file are correctly being put into your struct and you will soon be finished.
Related
I want my program to be aligned correctly; I'm using the iomanip (setw) library but I'm still getting the wrong output:
The output I want is:
1001 Butter 9.45 50 100 74
1002 Milk-1L 12.85 100 150 83
1003 Flour-Bak 13.45 210 500 410
The output I'm getting currently is:
1001 Butter 9.45 50 100 74
1002 Milk-1L 12.85 100 150 83
1003 Flour-Bak 13.45 210 500 410
Here is my code:
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
// Function Declaration
void displaymenu();
void Inventory();
void empgrossnet();
void employavgdeduc();
// Size of Array
const int SIZE = 10;
int i;
// Initialize Struct function for Employee Data
struct InventoryData {
int Itemnum;
string Name;
double UnitPrice;
int Minimumlevel;
int Optimumlevel;
int Qtyinstock;
} InventoryItems[SIZE];
// Initialize/Read file into the program
ifstream thefile("i_Data.txt");
int main() {
while (true) {
displaymenu();
}
return 0;
}
void displaymenu() {
int option;
// print menu options and prompt user to enter a menu option
printf("\n***************** Employee Data *******************\n");
printf("[1] Press 1 for Inventory Data Records\n");
printf("[2] Press 2 for Employee Gross and Net Pay\n");
printf("[3] Press 3 for Average Hours and Average Deductions\n");
printf("[4] Exit Program\n");
printf("\n****************************************************\n");
printf("\n Enter an option>>\t");
scanf("%d", &option);
switch (option) {
case 1:
Inventory();
break;
case 4:
printf("\n\n Thank you for using the Program");
printf("\n Exiting Application....");
exit(0);
}
}
void Inventory() {
// Read from edata.txt File
ifstream thefile("i_Data.txt");
// Check to make sure that Program is finding/reading from edata file
if (!thefile) {
cerr << "File can't be opened! " << endl;
system("PAUSE");
exit(1);
}
// Creat loop to store 5 lines of information from edata file
for (int i = 0; i < SIZE; i++) {
thefile >> InventoryItems[i].Itemnum >> InventoryItems[i].Name >>
InventoryItems[i].UnitPrice
>> InventoryItems[i].Minimumlevel >> InventoryItems[i].Optimumlevel >>
InventoryItems[i].Qtyinstock;
}
// Output/Display Edata file information into prgram
printf("\n************************************* EMPLOYEE DATA "
"****************************************\n");
printf("\n %s %15s %20s %15s %15s ", "EmployeeID", "Employee Name",
"Hours Worked", "Rate of Pay", "Deductions");
printf("\n-------------------------------------------------------------------"
"------------------\n");
for (int i = 0; i < SIZE; i++) {
cout << setw(10) << " " << InventoryItems[i].Itemnum;
cout << setw(10) << " " << InventoryItems[i].Name;
cout << setw(10) << " " << InventoryItems[i].UnitPrice;
cout << setw(10) << " " << InventoryItems[i].Minimumlevel;
cout << setw(10) << " " << InventoryItems[i].Optimumlevel;
cout << setw(10) << " " << InventoryItems[i].Qtyinstock << endl;
}
printf("\n-------------------------------------------------------------------"
"------------------\n");
}
You seem to want
cout <<" " << setw(10) << InventoryItems[i].Itemnum;
cout <<" " << setw(10) << InventoryItems[i].Name;
cout <<" " << setw(10) << InventoryItems[i].UnitPrice;
cout <<" " << setw(10) << InventoryItems[i].Minimumlevel;
cout <<" " << setw(10) << InventoryItems[i].Optimumlevel;
cout <<" " << setw(10) << InventoryItems[i].Qtyinstock<<endl;
Your original code outputs 10 spaces then values. I believe you want single spaces and values in 10-char placeholders.
I am a beginner in C++ programming. I need to create a program for a movie reservation system. I have done it until halfway through, but I am stuck at selecting the seats. I need to program it like the user must select a seat. The user can select seats for about 10 times in a loop. After selecting it, all the data should be stored in the text file, and in the line which I have stored the information about the particular movie. I am really hoping for a good suggestion to this problem. This is how I arrange the text file:
Avengers|1600|40|16
LoST World|3200|40|16
Titanic|6897|87|16
Avengers|1600|40|16
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
display_all()
{
char name [25];
char hours[25];
char seats[25];
fstream movie;
movie.open("Movies.txt",ios::in);
int count = 0;
string line;
ifstream file("Movies.txt");
while (getline(file, line))
count++;
int i = 0;
while(!movie.eof(), i++ , i<= count)
{
movie.getline(name,25,'|');
movie.getline(seats,25,'|');
movie.getline(hours,25);
cout<< "(" << i << ") " << name << "\n ";
}
return 0;
}
main()
{
char name [25];
char hours[25];
char seats[25];
char price[25];
char seats1[25];
char seats2[25];
char seats3[25];
char seats4[25];
char seats5[25];
char response = 'Y';
string customer, phone_number;
fstream movie;
movie.open("Movies.txt",ios::in);
char selection_role ;
int selection_movie ;
cout << " *************************************************************** " << endl;
cout << " MOVIE TICKET RESERVATION SYSTEM (MTRS) " << endl;
cout << " *************************************************************** " << endl;
cout << endl << endl ;
cout << " Please specify the selection : (1) CUSTOMER" << endl;
cout << " (2) MANAGEMENT" << endl;
cout << endl;
cout << " INPUT : ";
cin >> selection_role;
if (selection_role == 1);
cout << endl;
cout << "MOVIES AVAILABLE : ";
display_all();
cout << endl;
cout << "Please select a movie: ";
cin >> selection_movie ;
int i = 0;
while(i++ , i <= selection_movie)
{
movie.getline(name,25,'|');
movie.getline(seats,25,'|');
movie.getline(hours,25,'|');
movie.getline(price,25,'|');
}
cout << endl;
cout << "======You have selected " << name <<".=========" <<endl;
cout << endl;
cout << "Movie hours: " << seats << endl;
cout << "Number of seats available: " << hours << endl;
cout << " SCREEN "<<endl << endl;
cout << "1 2 3 4 5 6 7 8" <<endl << endl;
cout << "9 10 11 12 13 14 15 16"<<endl << endl;
cout << "17 18 19 20 21 22 23 24"<<endl << endl;;
cout << "25 26 27 28 29 30 31 32"<<endl << endl;
cout << "Enter the number of seat you would like to book for: ";
cin >> seats1 ;
cout << endl;
cout << "Price for the ticket: RM " << price << endl << endl;
cout << "Enter you name: " ;
cin >> customer ;
cout << "Enter your phone number: ";
cin >> phone_number;
cout << endl;
cout << " MOVIE TICKET " << endl;
cout << "============================" << endl;
cout << "Name :" << customer << endl;
cout << "Handphone number :" << phone_number <<endl;
cout << "Movie selected :" << name << endl;
cout << "Seat selected :" << seats1 <<"," << seats2 << endl;
cout << "Price for the movie(RM):" << price << endl;
}
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 am working on a shopping cart project, and I want to print out the user input like the following output. I don't know how to use setW and right/left keywords, when it comes to the user decides what the output is going to be like. So when they enter different inputs in length, for example setW(20) does not work for them all.
Here is your order:
----------------------------------------------------------------
Name Unit_Price Quantity
T-shirt $19.99 2
Sweater $39.99 1
iphone_case $25.5 3
Towel $9.99 5
The total charge is $206.42
----------------------------------------------------------------
This is the display function:
ostream& operator <<(ostream& os, Item& source) {
os << source.getName() << setw(18)
<< source.getPrice() << setw(20) << source.getQuantity() << endl;
return os;
}
And this is the output I get with this:
Here is your order:
----------------------------------------
NAME PRICE QUANTITY
tshirt 19.99 2
sweater 39.99 1
iphone_case 25.5 3
towel 9.99 5
The total price of the order is 206.42
----------------------------------------
And here is my main.cpp
#include "ShoppingCart.h"
#include "Item.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
cout << endl << endl << "Welcome to XXX SHOPPING CENTER" << endl;
Item items[10];
ShoppingCart<Item> cart;
char userAnswer;
cout << "Enter the item you selected as the following order:\nname unitPrice quantity\n"
<< "(Name can not contain any space. Otherwise errors happen!)" << endl;
cin >> items[0];
cart.add(items[0]);
cout << "Want to continue? y/n" << endl;
cin >> userAnswer;
int index = 1;
while(userAnswer == 'y' || userAnswer == 'Y') {
cout << "Enter the next item:" << endl;
cin >> items[index];
cart.add(items[index]);
cout << "Want to continue? y/n" << endl;
cin >> userAnswer;
index++;
}
// Display the summary of the orders
cout << endl << "Here is your order:" << endl;
// "--------------------------------------------------------------------"
for(int i=0; i < 40; i++)
cout << "-";
cout << endl << "NAME" << setw(18) << "PRICE" << setw(20) << "QUANTITY" << endl;
for(int i=0; i < cart.getCurrentSize(); i++) {
cout << items[i];
}
cout << endl << "The total price of the order is " << cart.getTotalPrice() << endl;
// "---------------------------------------------------------------------"
for(int i=0; i < 40; i++)
cout << "-";
cout << endl;
return 0;
}
The strategy you are using does not make sense to me. Here's one way to get the desired output:
Use 20 characters for the first column and make sure that it is output with left aligned text.
Use 10 characters for the second and third columns, and make sure they are output with right aligned text.
Use std::left and std::right to control text alignment.
Here's a simplified program that demonstrates the idea.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
struct Item
{
std::string name;
double price;
int quantity;
};
std::ostream& operator<<(std::ostream& out, Item const& item)
{
// First column
out << std::left << std::setw(20) << item.name;
// Second and third columns
out << std::right << std::setw(10) << item.price << std::setw(10) << item.quantity;
return out;
}
void printLine(std::ostream& out)
{
for(int i=0; i < 40; i++)
out << "-";
out << std::endl;
}
int main()
{
std::vector<Item> items;
items.push_back({"tshirt", 19.99, 2});
items.push_back({"sweater", 39.99, 1});
items.push_back({"iphone_case", 25.50, 3});
items.push_back({"towel", 9.99, 5});
printLine(std::cout);
// First column
std::cout << std::left << std::setw(20) << "NAME"
// Second and third columns
std::cout << std::right << std::setw(10) << "PRICE" << std::setw(10) << "QUANTITY" << std::endl;
// The items
for(int i=0; i < 4; i++) {
std::cout << items[i] << std::endl;
}
printLine(std::cout);
}
Output:
----------------------------------------
NAME PRICE QUANTITY
tshirt 19.99 2
sweater 39.99 1
iphone_case 25.5 3
towel 9.99 5
----------------------------------------
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...