Resetting output flags in C++ - c++

I'm intending to reset all output flags to default on the lines where I end using the resetiosflags function. It provides erroneous output when I attempt to do it in this manner, contrary to my expectations.
#include <iostream>
#include <iomanip>
using namespace std;
int
main()
{
bool first;
int second;
long third;
float fourth;
float fifth;
double sixth;
cout << "Enter bool, int, long, float, float, and double values: ";
cin >> first >> second >> third >> fourth >> fifth >> sixth;
cout << endl;
// ***** Solution starts here ****
cout << first << " " << boolalpha << first << endl << resetiosflags;
cout << second << " " << showbase << hex << second << " " << oct << second << endl << resetiosflags;
cout << third << endl;
cout << showpos << setprecision(4) << showpoint << right << fourth << endl << resetiosflags;
cout << scientific << fourth << endl << resetiosflags;
cout << setprecision(7) << left << fifth << endl << resetiosflags;
cout << fixed << setprecision(3) << fifth << endl << resetiosflags;
cout << third << endl;
cout << fixed << setprecision(2) << fourth << endl << resetiosflags;
cout << fixed << setprecision(0) << sixth << endl << resetiosflags;
cout << fixed << setprecision(8) << fourth << endl << resetiosflags;
cout << setprecision(6) << sixth << endl << resetiosflags;
// ***** Solution ends here ****
cin.get();
return 0;
}
My known alternative is de-flagging them individually by restating them, but that seems superfluous.

/*unspecified*/ resetiosflags( std::ios_base::fmtflags mask );
std::resetiosflags() is a manipulator intended to be used in an expression such as out << resetiosfloags( flags ). Presumably what you're doing is passing in a function pointer, which gets selected by the overload of std::operator<< that takes a boolean and prints 1.
But std::resetiosflags() takes a format flags as a parameter which the precision can't be manipulated with. std::ios_base::boolalpha can, however:
std::cout << ... << std::resetiosflags(std::ios_base::boolalpha);
There's also std::noboolalpha
std::cout << ... << std::noboolalpha;
But if you need to reset the precision to its default you can just create your own manipulator for that. You can also use Boost IO State Saver.

Related

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++ aligning characters to display neatly with any input implemented

I am having trouble keeping the ":" and the "$" aligned with whichever input the user implements through the cin command which is "numTShirts". It stays aligned if implemented 10 and under but discount goes out of place with any other input.
![implemented with 10] http://prntscr.com/gzms3m
![implemented with other] http://prntscr.com/gzmsjx
cout << "\n" << endl;
cout << fixed;
cout << "Thank you for your purchase.\n" << endl;
cout << "You bought " << numTShirts << " T-shirts\n" << endl;
cout << "Subtotal Total" << setw(5) << ": $ " << right << setprecision(2) << subTotal << "\n" << endl;
cout << setprecision(0) << "Discount(" << discountPCT << "%)" << setw(7) << ": $ " << right << showpoint << setprecision(2) << discount << "\n" << endl;
cout << setfill('-') << setw(35) << "-\n" << endl;
cout << setfill(' ');
cout << "Total" << setw(14) << ": $ " << right << showpoint << setprecision(2) << totalPrice << endl;
This is happening because the amount of discount is variable and according to it the space increases.
As you show in the example when the discount is of one digit the aligning is the desired one, otherwise it is different.
As the discoutn can be maximum of three digits (100%) then I'd suggest you two make three formatting of the output.
one for 1 digit discount, 2 digit and 3 digit.
by using a conditional statement you can show the respective in the output.

Having trouble with iomanip, columns not lining up the way I expect

finishing up a long project and the final step is to make sure my data lines up in the proper column. easy. Only I am having trouble with this and have been at it for longer than i wish to admit watching many videos and can't really grasp what the heck to do So here is a little snippet of the code that I'm having trouble with:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
cout << "Student Grade Summary\n";
cout << "---------------------\n\n";
cout << "BIOLOGY CLASS\n\n";
cout << "Student Final Final Letter\n";
cout << "Name Exam Avg Grade\n";
cout << "----------------------------------------------------------------\n";
cout << "bill"<< " " << "joeyyyyyyy" << right << setw(23)
<< "89" << " " << "21.00" << " "
<< "43" << "\n";
cout << "Bob James" << right << setw(23)
<< "89" << " " << "21.00" << " "
<< "43" << "\n";
}
which works for the first entry but the bob james entry has the numbers all askew. I thought setw was supposed to allow you to ignore that? What am i missing?
Thanks
It doesn't work as you think. std::setw sets the width of the field only for the next insertion (i.e., it is not "sticky").
Try something like this instead:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "Student Grade Summary\n";
cout << "---------------------\n\n";
cout << "BIOLOGY CLASS\n\n";
cout << left << setw(42) << "Student" // left is a sticky manipulator
<< setw(8) << "Final" << setw(6) << "Final"
<< "Letter" << "\n";
cout << setw(42) << "Name"
<< setw(8) << "Exam" << setw(6) << "Avg"
<< "Grade" << "\n";
cout << setw(62) << setfill('-') << "";
cout << setfill(' ') << "\n";
cout << setw(42) << "bill joeyyyyyyy"
<< setw(8) << "89" << setw(6) << "21.00"
<< "43" << "\n";
cout << setw(42) << "Bob James"
<< setw(8) << "89" << setw(6) << "21.00"
<< "43" << "\n";
}
Also related: What's the deal with setw()?
The manipulators << right << setw(23) are telling the ostream that you want
the string "89" set in the right-hand edge of a 23-character-wide field.
There is nothing to tell the ostream where you want that field to start,
however, except for the width of the strings that are output since the
last newline.
And << "bill"<< " " << "joeyyyyyyy" writes a lot more characters to the output
than << "Bob James" does, so the 23-character-wide field on the second line
starts quite a bit to the left of the same field on the first line.
Stream manipulators affect the next input/output value being streamed, and then some manipulators (including setw()) reset afterwards. So you need to set the width and alignment BEFORE you output a text string, not afterwards.
Try something more like this:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void outputStudent(const string &firstName, const string &lastName,
int finalExam, float finalAvg, int letterGrade)
{
cout << setw(40) << left << (firstName + " " + lastName) << " "
<< setw(6) << right << finalExam << " "
<< setw(6) << right << fixed << setprecision(2) << finalAvg << " "
<< setw(7) << right << letterGrade << "\n";
}
int main()
{
cout << "Student Grade Summary\n";
cout << "---------------------\n\n";
cout << "BIOLOGY CLASS\n\n";
cout << "Student Final Final Letter\n";
cout << "Name Exam Avg Grade\n";
cout << "--------------------------------------------------------------\n";
outputStudent("bill", "joeyyyyyyy", 89, 21.00, 43);
outputStudent("Bob", "James", 89, 21.00, 43);
cin.get();
return 0;
}
Output:
Student Grade Summary
---------------------
BIOLOGY CLASS
Student Final Final Letter
Name Exam Avg Grade
--------------------------------------------------------------
bill joeyyyyyyy 89 21.00 43
Bob James 89 21.00 43

How to use setw and setfill together in C++ to pad with blanks AND chars?

I need to write a program for a homework assignment to calculate tuition costs and the output should be formatted like so with the dot padding and space padding after the dollar sign:
Student Name: Name goes here
Address: Address goes here
Number of credits: .......... 5
Cost per credit hour: ............ $ 50
My code so far is:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
double const REG_FEE = 700, STUDENT_ASSEMBLY_FEE = 7.19, LEGAL_FEE = 8.50, STUDGOV_FEE = 1.50,
LATE_FEE_PERCENTAGE = 0.015;
int main()
{ double num_credits, cost_per_credit, tuition_total, late_charge, amount_due;
string student_name;
string student_address;
string student_city_state_ZIP;
ifstream info;
info.open ("info.txt");
getline (info, student_name);
getline (info, student_address);
getline (info, student_city_state_ZIP);
info >> num_credits;
info >> cost_per_credit;
tuition_total = num_credits * cost_per_credit + REG_FEE + STUDENT_ASSEMBLY_FEE + LEGAL_FEE
+ STUDGOV_FEE;
late_charge = tuition_total * LATE_FEE_PERCENTAGE;
amount_due = tuition_total + late_charge;
cout << "Tuition and Billing Program by Neal P." << endl
<< setw(18) << "Student Name:" << student_name << endl
<< setw(18) << "Address:" << student_address << endl
<< left << setfill('.') << endl
<< setfill(18) << "Number of Credits:" << setw(5) << "$" << num_credits << endl
<< setfill(18) << "Cost per Credit Hour:" << setw(5) << "$" << cost_per_credit << endl
<< setfill(18) << "Tuition Cost:" << setw(5) << "$" << tuition_total << endl
<< setfill(18) << "Registration Fee:" << setw(5) << "$" << REG_FEE << endl
<< setfill(18) << "MSA Fee:" << setw(5) << "$" << STUDENT_ASSEMBLY_FEE << endl
<< setfill(18) << "Legal Services Fee:" << setw(5) << "$" << LEGAL_FEE << endl
<< setfill(18) << "Student Government Fee:" << setw(5) << "$" << STUDGOV_FEE << endl;
return 0;
}
When I compile I get a very long error, something like : "In function ‘int main()’:
/Users/nealp/Desktop/machine problem 2.cpp:41: error: no match for ‘operator<<’ in ‘((std::basic_ostream >*)std::operator<< [with _CharT = char, _Traits = std::char_traits](((std::basic_ostream >&)((std::basic_ostream >*)((std::basic_ostream >*)((std::basic_ostream >*)std::operator<<" that continues.
Is this an issue with my use of both setw and setfill together? I know that setfill only has to be declared once and setw is only effective on the next line output, but I defined setfill each time because I was using setw before it.
std::setfill is a function template and it's template argument gets deduced based on the type of the argument you pass it to. It's return type is unspecified - it's some implementation defined proxy type that sets fill character on the stream object and enables further chaining of operator<< calls. It's also dependent on the type that setfill gets instantiated with.
The type of literal 18 is int so setfill returns some unrelated type for which there's no operator<< avaliable.
I'm not sure what you meant with setfill(18), I'm guessing you've mistaken it for setw(18).
Just replace setfill(18) in your code, that is the reason for compilation error.
Here is the improved printing portion to fit the requirements,
cout << "Tuition and Billing Program by Neal P." << endl
<< "Student Name:" << student_name << endl
<< "Address:" << student_address << endl
<<endl<<endl<< "Number of Credits:" << setfill('.') << setw(5) <<"$" << num_credits
<< endl<< "Cost per Credit Hour:"<<setfill('.')<<setw(5)<< "$" << cost_per_credit <<
endl<< "Tuition Cost:" << setfill('.')<<setw(5)<< "$" << tuition_total << endl
<< "Registration Fee:" << setfill('.')<<setw(5) << "$" << REG_FEE << endl
<< "MSA Fee:" << setfill('.')<<setw(5) << "$" << STUDENT_ASSEMBLY_FEE << endl
<< "Legal Services Fee:" << setfill('.')<<setw(5) << "$" << LEGAL_FEE << endl
<< "Student Government Fee:" << setfill('.')<<setw(5) << "$" << STUDGOV_FEE << endl;

C++ setw moving whole line not just the needed part

I am trying to use setw to clean up the output of my program. I want the empty spaces in between "total number of spools to be ordered" and the output.
EDIT this is what im going for:
and this is what I get
here is what I have so far:
UPDATED CODE
/********************************************/
// Name: results /
// Description: Print results /
// Parameters: N/A /
// Reture Value: N/A /
/********************************************/
void results(int spoolnumber, int subtotalspool, float shippingcost, float totalcost)
{
cout << left << setw (45) << "Total number of spools to be ordered is: " << right << spoolnumber << endl << endl;
cout << left << setw (45) << "The subtotal for the spools is:" << right << "$" << subtotalspool << endl << endl;
cout << "The shipping cost is: $" << shippingcost << endl << endl;
cout << "The total cost is: $" << totalcost << endl << endl;
return;
}
You can also do
cout << left << setw (45) << "Total number of spools to be ordered is: " << spoolnumber << endl << endl;
to choose which side the padding goes. The default is left.
EDIT: using stringstream
stringstream ss;
ss << "$" << spoolnumber
I think you can fix the right end by adding another setw. So:
cout << left << setw (45) << "Total number of spools to be ordered is: " << right << setw(5) << ss.str() << endl << endl;