I am having trouble with using getline - c++

I am having trouble with my code not reading the whole string name.
I have tried using getline(cin, movieName) as well as cin.ignore(), but I can't get it to work properly.
I am taking a beginner's course to this class, but my professor does not answer their emails.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string movieName;
const float adultTicketPrice = 12;
const float childTicketPrice = 6;
const float percentTheaterKeeps = .20;
int adultTicketsSold, childTicketsSold;
float grossProfit, netProfit, amountPaidToDistributor;
getline(cin, movieName);
cout << fixed << showpoint << setprecision(2);
cout << "What movie played tonight?\t ";
cin >> movieName;
cout << "How many adult tickets were sold? ";
cin >> adultTicketsSold;
cout << "How many child tickets were sold? ";
cin >> childTicketsSold;
grossProfit = adultTicketPrice * adultTicketsSold + childTicketPrice * childTicketsSold;
netProfit = grossProfit * percentTheaterKeeps;
amountPaidToDistributor = grossProfit - netProfit;
cout << setw(10) << left << "Movie Name";
cout << setw(23) << right << movieName << endl;
cout << setw(10) << left << "Adult Tickets Sold";
cout << setw(16) << right << adultTicketsSold << endl;
cout << setw(10) << left << "Child tickets sold";
cout << setw(16) << right << childTicketsSold << endl;
cout << setw(10) << left << "Gross Box Office Profit";
cout << setw(11) << right << grossProfit << endl;
cout << setw(10) << left << "Net Box Office Profit";
cout << setw(13) << right << netProfit << endl;
cout << setw(10) << left << "Amount Paid to distributor";
cout << setw(8) << right << amountPaidToDistributor << endl << endl;
return 0;
}

You need to use std::getline(std::cin, movieName) when you want to get input for movieName.
Presumably you're seeing a blank line when you start your program, and pressing enter. This sets movieName to '\n'. Remove that line, and switch std::cin >> movieName; with std::getline(std::cin, movieName). (Remove the std::s if you're using a using declaration)

Related

setw(n) and alignment not working the way I need it to - C++

Here is my code for context. This is my second homework assignment intro to programming course and I have used everything we've learned in this assignment. I am not allowed to use anything I have not learned.
The part I am concerned with is the output at the very bottom (commented as information output). Currently, I am struggling to get everything perfectly right aligned (the last letter or number in the right hand column must align with each other as if I were typing them from the right.
Everything except the patient's name, room type, and days spent in the hospital are aligning properly, decimals aligned and everything. Changing the setw(10) to anything larger does nothing beneficial (ex: i had all of them to setw(40) and it still did not align anything properly. Any ideas?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//constants
const float PRIVATE = 125.00;
const float SEMI = 95.00;
const float WARD = 75.00;
const float TV = 3.50;
const float PHONE = 1.75;
int main()
{ //local variables
string fname, lname, roomType, tvAccess, phoneAccess;
int id, days;
float roomBill, roomPrice, tvCharge, phoneCharge;
bool error = false;
//data collection/output
cout << "Welcome to the hospital self-service program. Your bill will be calculated here.\n\n" << endl;
cout << "Please enter your first and last name: ";
cin >> fname;
cin >> lname;
cout << fname << " " << lname << ", please enter the four digit identification number found on your hospital wristband: ";
cin >> id;
cout << "Please enter the number of days spent in the hospital: ";
cin >> days;
cout << "\nEnter the type of room you stayed in: \nEnter P for room type: Private \nEnter S for room type: Semi-Private\nEnter W for room type: Ward \n" << endl;
cin >> roomType;
cout << "\nDid your room come with access to Television? Y/N: ";
cin >> tvAccess;
cout << "Did your room come with access to a Telephone? Y/N: ";
cin >> phoneAccess;
//if and elses
if (roomType == "P" || roomType == "p")
{
error = false;
roomType = "Private Room";
roomPrice = PRIVATE;
}
else if (roomType == "S" || roomType == "s")
{
error = false;
roomType = "Semi-Private Room";
roomPrice = SEMI;
}
else if (roomType == "W" || roomType == "w")
{
error = false;
roomType = "Ward Room";
roomPrice = WARD;
}
else
{
cout << "Room type not valid. Exit the program and try again." << endl;
error = true;
}
if (tvAccess == "Y" || tvAccess == "y")
tvCharge = TV;
else
tvCharge = 0;
if (phoneAccess == "Y" || phoneAccess == "y")
phoneCharge = PHONE;
else
phoneCharge = 0;
//information output
cout << fixed << setprecision(2) << showpoint << endl;
cout << setw(24) << left << "\n\nPatient Full Name: " << setw(10) << right << fname << " " << lname << endl;
cout << setw(24) << left << "Identification Number: " << setw(10) << right << id << endl;
cout << setw(24) << left << "Days spent in hospital: " << setw(10) << right << days << " day(s)" << endl;
cout << setw(24) << left << "Room Type: " << setw(10) << right << roomType << endl;
cout << setw(24) << left << "Room Charge: " << setw(10) << right << roomPrice * days << endl;
cout << setw(24) << left << "Television Charge: " << setw(10) << right << tvCharge * days << endl;
cout << setw(24) << left << "Telephone Charge: " << setw(10) << right << phoneCharge * days << endl;
cout << setw(24) << left << "Total Charge: " << setw(10) << right << days * (phoneCharge + tvCharge + roomPrice) << endl;
system("pause");
return 0;
}
for clarification.
The reason, they are not formatted correctly, is, that the setw in
setw(10) << right << fname << " " << lname << endl;
and
setw(10) << right << days << " day(s)" << endl;
only applies to the first variable, i.e. fname and days. Everything else is just appended. You need to concatenate these strings first before using setw here.

Basic C++ Application has extra output then it should

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

(C++) Rows in my columns aren't showing up after the first iteration

I'm 2 days news to programming and this is my first post, so I'd greatly appreciate your help and patience. :)
My current assignment is to have a user input 2 items bought from a store, including price and quantity, to generate a receipt. For some reason, I can't get any of my code to display after the first item's info gets displayed.
#include <iostream>
#include <iomanip> // For column organization
#include <string> // For item names
using namespace std;
const float TAX = 0.08675;
int main()
{
string itemOne, itemTwo;
double priceOne, priceTwo;
int countOne, countTwo;
cout << "Hello, what is the first item that you are purchasing today?" << endl;
cout << "Please enter the item below." << endl;
getline(cin, itemOne);
cout << endl << "Thank you." << endl;
cout << "Now enter the price and then the quantity of " + itemOne + "(s) purchased, separated by a space." << endl;
cin >> priceOne >> countOne;
cin.ignore();
cout << endl << "What is the second item that you are purchasing today?\n";
cout << "Please enter the item below." << endl;
getline(cin, itemTwo);
cout << endl << "Thank you." << endl;
cout << "Now enter the price and then the quantity of " + itemTwo + "(s) purchased, separated by a space." << endl;
cin >> priceTwo >> countTwo;
/* Calculations for the Receipt */
float subTotal, finalPriceOne, finalPriceTwo, salesTax, finalTotal;
finalPriceOne = countOne * priceOne;
finalPriceTwo = countTwo * priceTwo;
subTotal = finalPriceOne + finalPriceTwo;
salesTax = subTotal * TAX;
finalTotal = subTotal + salesTax;
/* Receipt */
cout << endl << "Your receipt has been calculated and is for your viewing below..." << endl << endl;
cout << "---------------------------------------------------------------\n";
cout << left << setw(15) << "Item";
cout << right << setw(15) << "Quantity";
cout << right << setw(15) << "Price";
cout << right << setw(15) << "Ext. Price";
cout << endl;
cout << "---------------------------------------------------------------\n";
cout << setprecision(2) << fixed;
cout << left << setw(15) << itemOne;
cout << right << setw(15) << countOne;
cout << right << setw(15) << priceOne;
cout << right << setw(15) << finalPriceOne;
cout << endl;
cout << left << setw(15) << itemTwo;
cout << right << setw(15) << countTwo;
cout << right << setw(15) << priceTwo;
cout << right << setw(15) << finalPriceTwo;
cout << endl;
cout << left << setw(15) << "Tax";
cout << right << setw(15) << salesTax;
cout << endl;
cout << left << setw(15) << "Total";
cout << right << setw(15) << finalTotal;
cout << endl;
return 0;
}
On my computer (Windows g++ CodeBlocks) everything is fine. The problem surely comes from your IDE. Here is your code output on my screen :
Just for information, try to use C++ functionalities as POO to dsign your objects. It will be easier for you when coding bigger applications.
I think your execution is just paused at that breakpoint on the endl for the second item. If you step past it (or just remove the breakpoint), does the whole line for the second item appear? If so, it's because of something called "line buffering", where the program doesn't actually output as soon as you tell it to, but instead it collects up things until it sees a line-ending and then it outputs the whole line.
(Breakpoints, in case it's something you did by accident, are a feature of interactive debugging systems where you can have the whole program pause before executing a given line of code. They're often set in IDEs via a right-click menu or a click in the margin next to the line of code.)

How do I properly format C++ floats to two decimal places?

I'm having some issues using setprecision. I don't understand how it works completely. I searched the problem and was able to extrapolate some code that should've worked. I don't understand why it's not. Thank you for your help, I'm still kind of new at this.
//monthly paycheck.cpp
//Paycheck Calculator
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
//Constants
const double
FEDERAL_TAX = 0.15, //Federal Tax
STATE_TAX = 0.035, //State Tax
SSA_TAX = 0.085, //Social Security & Medicare
HEALTH_INSURANCE = 75; //Health Insurance
//Variables
int year;
double grossAmount;
string employeeName, month;
// Initialize variables with input
cout << "Hello, what's your first name? ";
cin >> employeeName;
cout << "What is your gross amount? ";
cin >> grossAmount;
cout << "Please enter the month and year: ";
cin >> month >> year;
// Output
cout << "***********************************" << endl;
cout << "Paycheck" << endl;
cout << "Month: " << month << "\tYear: " << year << endl;
cout << "Employee Name: " << employeeName << endl;
cout << "***********************************" << endl;
cout << setprecision(5) << fixed;
cout << "Gross Amount: $" << grossAmount << endl;
cout << "Federal Tax: $" << FEDERAL_TAX*grossAmount << endl;
cout << "State Tax: $" << STATE_TAX*grossAmount << endl;
cout << "Social Sec / Medicare: $" << SSA_TAX*grossAmount << endl;
cout << "Health Insurance: $" << HEALTH_INSURANCE << endl << endl;
cout << "Net Amount: $" << fixed << grossAmount-grossAmount*(FEDERAL_TAX+STATE_TAX+SSA_TAX)-HEALTH_INSURANCE << endl << endl;
system("PAUSE");
return 0;
}
If you want to format floats to display with 2 decimal places in C++ streams, you could easily:
float a = 5.1258f;
std::cout << std::fixed << std::setprecision(2) << a << std::endl;
See std::fixed and std::setprecision
Use stream manipulators:
std::cout.fixed;
std::cout.precision(Number_of_digits_after_the_decimal_point);

How would I go about outputting the output from ALL of the above code?

Basically I want an exact copy of the code that appears in the console window to also be outputted to a txt file..
#include <conio.h>
#include <iostream>
#include <dos.h>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <fstream>
using namespace std;
//Initialising gotoxy Comand
void gotoxy(int col, int row)
{
COORD coord;
coord.X = col;
coord.Y = row;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
char name1[20], name2[20], name3[30], name4[20];
int funcNum = 0;
int n1Nv, n1Mv, n1SEv, n1SWv;
int n2Nv, n2Mv, n2SEv, n2SWv;
int n3Nv, n3Mv, n3SEv, n3SWv;
int n4Nv, n4Mv, n4SEv, n4SWv;
int n1Total, n2Total, n3Total, n4Total, perTotal;
double n1Per, n1PerTotal;
double n2Per, n2PerTotal;
double n3Per, n3PerTotal;
double n4Per, n4PerTotal;
double maxVote;
//Introduction
cout << "================================================================================";
cout << " Ballot Results" << endl;
cout << " Version 2.1" << endl;
cout << " Created by Team b0nkaz" << endl;
cout << "================================================================================" << endl;
//Candidate Identification
cout << "Enter the candidates running for president" << endl << endl;
//cin.getline (workaround,30); //**
cout << "Candidate One: ";
cin.getline (name1,20);
cout << "Candidate Two: ";
cin.getline (name2,20);
cout << "Candidate Three: ";
cin.getline (name3,20);
cout << "Candidate Four: ";
cin.getline (name4,20);
cout << " " << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
cout << "Input vote numbers from each region pressing enter after each input:" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
//Input Table
//Regions
gotoxy(22,19);
cout << "North" << endl;
gotoxy(31,19);
cout << "Midlands" << endl;
gotoxy(43,19);
cout << "South East" << endl;
gotoxy(57,19);
cout << "South West" << endl;
gotoxy(69,19);
cout << "| Total" << endl;
cout << "_____________________________________________________________________|__________" << endl;
gotoxy(69,21);
cout << "|";
gotoxy(69,22);
cout << "|";
gotoxy(69,23);
cout << "|";
gotoxy(69,24);
cout << "|";
gotoxy(69,25);
cout << "|";
gotoxy(69,25);
cout << "|";
gotoxy(69,26);
cout << "|";
gotoxy(69,27);
cout << "|";
gotoxy(69,28);
cout << "|";
gotoxy(69,29);
cout << "|";
//Candidates
gotoxy(0,22);
cout << name1;
gotoxy(0,24);
cout << name2;
gotoxy(0,26);
cout << name3;
gotoxy(0,28);
cout << name4;
//Equals
cout << endl;
cout << "_____________________________________________________________________|__________" << endl;
//Vote Input
//North
gotoxy(22,22);
cin >> n1Nv;
gotoxy(22,24);
cin >> n2Nv;
gotoxy(22,26);
cin >> n3Nv;
gotoxy(22,28);
cin >> n4Nv;
//Midlands
gotoxy(31,22);
cin >> n1Mv;
gotoxy(31,24);
cin >> n2Mv;
gotoxy(31,26);
cin >> n3Mv;
gotoxy(31,28);
cin >> n4Mv;
//South East
gotoxy(43,22);
cin >> n1SEv;
gotoxy(43,24);
cin >> n2SEv;
gotoxy(43,26);
cin >> n3SEv;
gotoxy(43,28);
cin >> n4SEv;
//South West
gotoxy(57,22);
cin >> n1SWv;
gotoxy(57,24);
cin >> n2SWv;
gotoxy(57,26);
cin >> n3SWv;
gotoxy(57,28);
cin >> n4SWv;
//Total Votes
//Name1
gotoxy(72,22);
n1Total = n1Nv + n1Mv + n1SEv + n1SWv;
cout << n1Total;
//Name2
gotoxy(72,24);
n2Total = n2Nv + n2Mv + n2SEv + n2SWv;
cout << n2Total;
//Name3
gotoxy(72,26);
n3Total = n3Nv + n3Mv + n3SEv + n3SWv;
cout << n3Total;
//Name4
gotoxy(72,28);
n4Total = n4Nv + n4Mv + n4SEv + n4SWv;
cout << n4Total << endl << endl << endl;
//Percentage Calculation
perTotal = n1Total + n2Total + n3Total + n4Total;
//Candidate One
n1Per = n1Total*100;
n1PerTotal = n1Per/perTotal;
//Candidate Two
n2Per = n2Total*100;
n2PerTotal = n2Per/perTotal;
//Candidate Three
n3Per = n3Total*100;
n3PerTotal = n3Per/perTotal;
//Candidate Four
n4Per = n4Total*100;
n4PerTotal = n4Per/perTotal;
cout << "Please wait for calculation..." << endl << endl;
//Spinning Loading Line
//std::cout << '-' << std::flush;
//for(;;)
//{
//Sleep(100);
//std::cout << "\b\\" << std::flush;
//Sleep(100);
//std::cout << "\b|" << std::flush;
//Sleep(100);
//std::cout << "\b/" << std::flush;
//Sleep(100);
//std::cout << "\b-" << std::flush;
//}
//Sleeping Program
Sleep(1500); //1.5 secs
//Total Output
cout << "Candidate percentage:" << endl << endl;
//Converting To One Decimal Place
cout << fixed;
std::cout.precision(1);
//Vote Percentages
cout << name1 << " = " << n1PerTotal << "%" << endl;
cout << name2 << " = " << n2PerTotal << "%" << endl;
cout << name3 << " = " << n3PerTotal << "%" << endl;
cout << name4 << " = " << n4PerTotal << "%" << endl << endl;;
//Calculating Winnner
maxVote=n1PerTotal;
if (n2PerTotal>maxVote)
maxVote=n2PerTotal;
if (n3PerTotal>maxVote)
maxVote=n3PerTotal;
if (n4PerTotal>maxVote)
maxVote=n4PerTotal;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
//Sleeping Program
Sleep(1500); //1.5 secs
if(maxVote==n1PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name1 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n1PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n2PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name2 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n2PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n3PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name3 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n3PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n4PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name4 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n4PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
cout << "Press any key to exit..." << endl;
getch();
//system("pause");
}
I am using MS Visual Studio 2010 and any help would be great! Please note I am still very new to C++.
EDIT I would like to be able to see the output in CMD as well as have a separate txt file with the same output code. Everything that is displayed in the CMD window also copied into the txt file.
use an ofstream operator as such.
For some reason I can't seem to find the comment button or I would be involved in the discussion above... but I've edited my code below to reflect what seem to be some concerns of yours.
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("data.txt"); //Will create a new file if one is not already in existence
//You can put a static filename here or have them enter a string
//If you use a custom string your input will be "fout.open(STRING.c_str());
fout<<"Used exactly like cout from this point on";
fout.close(); //When you are done using it to close the file
}
I chose to name my ofstream operator fout because (while this is not always good to do) this way you can quickly change all of your cout's to fout's, or replicate them.
If the user enters a value and you want to spit it back out as well, you can use the ofstream operator after every cin.
You can find more information about ofstream here...
Hope this helped!
You can do this from outside of the application using tee. tee takes the output of a program and splits it into two streams (e.g. one to stdout and one to a file). Unfortunately, Windows doesn't come with a tee command but there are many implementations available.
If you want this to happen from within your program you can do the equivalent of tee using a custom ofstream. This article explains how.