C to C++ printf - c++

How would I change this code, preserving formatting to C++ using cout?
printf(" %5lu %3d %+1.2f ", nodes, depth, best_score / 100.0);

To be honest, I've never liked the ostream formatting mechanism. I've tended to use boost::format when I need to do something like this.
std::cout << boost::format(" %5lu %3d %+1.2f ") % nodes % depth % (best_score / 100.0);

#include <iostream>
#include <iomanip>
void func(unsigned long nodes, int depth, float best_score) {
//store old format
streamsize pre = std::cout.precision();
ios_base::fmtflags flags = std::cout.flags();
std::cout << setw(5) << nodes << setw(3) << depth;
std::cout << showpos << setw(4) << setprecision(2) << showpos (best_score/100.);
//restore old format
std::cout.precision(pre);
std::cout.flags(flags);
}

Use cout.width(n) and cout.precision(n);
So, for example:
cout.width(5);
cout << nodes << " ";
cout.width(3);
cout << depth << " ";
cout.setiosflags(ios::fixed);
cout.precision(2);
cout.width(4);
cout << best_score/100.0 << " " << endl;
You can chain things together:
cout << width(5) << nodes << " " << width(3) << depth << " "
<< setiosflags(ios::fixed) << precision(2) << best_score/100.0 << " "
<< endl;

Related

How can I display a $ sign with a value while using setw and setprecision in c++

I want to display the dollar sign next to its value in the second column, but if I convert the value into a string, the setprecision doesn't work and it displayed more decimals than I would like. Currently the formatting doesn't look good.
My current code:
string unit = "m";
double width = 30.123;
double length = 40.123;
double perimeter = 2 * width + 2 * length;
double area = width * length;
double rate = (area <= 3000) ? 0.03 : 0.02;
double cost = area * rate;
const int COLFMT = 20;
cout << fixed << setprecision(2);
cout << setw(COLFMT) << left << "Length:"
<< setw(COLFMT) << right << length << " " << unit << endl;
cout << setw(COLFMT) << left << "Width:"
<< setw(COLFMT) << right << width << " " << unit << endl;
cout << setw(COLFMT) << left << "Area:"
<< setw(COLFMT) << right << area << " square" << unit << endl;
cout << setw(COLFMT) << left << "Perimeter:"
<< setw(COLFMT) << right << perimeter << " " << unit << endl;
cout << setw(COLFMT) << left << "Rate:"
<< setw(COLFMT) << right << rate << "/sqaure" << unit << endl;
cout << setw(COLFMT) << left << "Cost:"
<< setw(COLFMT) << right << "$" << cost << endl;
Produces this poorly formatted output:
Length: 40.12 m
Width: 30.12 m
Area: 1208.63 square m
Perimeter: 140.49 m
Rate: 0.03/square m
Cost: $36.26
"Currently the formatting doesn't look good."
That's because std::right pertains to what follows it, in your case "$". So the dollar sign is right-aligned and not the value that follows on afterwards.
What you want is the fully formatted monetary value "$36.26" to be right aligned. So build that up as a string first with stringstream.
stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;

I want to align my results in columns based on the decimal place

I want to display my result aligned on the column by the decimal place.
I have tried to just put setw(7) and setw(6) in parts of the display but it seems to not change the output at all.
int main()
{
double x;
char more = 'y';
while(more=='y' || more=='Y')
{
cout << "\n\t\t\tInput x:";
cin >> x;
cout << "\n\n\t\t\t LibraryResult\tMyResult" << endl;
cout << setprecision(2) << fixed << "\n\t\tsin(" << x << ")\t"
<< setprecision(6) << sin(x) << "\t" << mySin(x) << endl;
cout << setprecision(2) << fixed << "\n\t\tcos(" << x << ")\t"
<< setprecision(6) << cos(x) << "\t" << myCos(x) << endl;
cout << setprecision(2) << fixed << "\n\t\texp(" << x << ")\t"
<< setprecision(6) << exp(x) << "\t" << myExp(x) << endl;
}
}
I want the resultants of the program to be aligned by decimal, so when you put in a number like 2 the decimals are all in the same column.
If you set a precision of 6, a width of 6 or 7 is simply not enough to contain the number. You have to either reduce the precision or increase the width.
Try playing around with the stream manipulators in the following snippet
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
int main()
{
const double period = 2 * 3.141592653589793;
const int steps = 20;
std::cout << std::string(44, '=') << '\n';
std::cout << std::setw(3) << "x" << std::setw(12) << "sin(x)"
<< std::setw(12) << "cos(x)" << std::setw(14) << "tan(x)" << '\n';
std::cout << std::string(44, '-') << '\n';
for(int i = 0; i <= steps; ++i)
{
double x = i * period / steps;
std::cout << std::setprecision(2) << std::fixed << x
<< std::setprecision(6) << std::setw(12) << std::sin(x)
<< std::setprecision(6) << std::setw(12) << std::cos(x)
<< std::setprecision(6)
<< std::setw(16) // <- Try to decrease it
<< std::scientific // <- Try to keep it as std::fixed
<< std::tan(x) << '\n';
}
std::cout << std::string(44, '-') << '\n';
}
You must use several manipulators (one is not enough)
You might want to try with the following combination, that right-aligns your numbers, with a fixed number of decimals.
std::cout.width(15);
std::cout << std::fixed << std::setprecision(6) << std::right << exp(x) << std::endl;
You can find information about manipulators 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

How do I find the sum using a loop function?

I was able to loop a file that gave me the miles driven, gallons used, and gasoline cost at a certain day successfully. Now I'm trying to figure out how to get the sum of miles driven, gallons used, and gasoline cost by using loops
int main()
{
ifstream inputFile;
int x = 1;
int milesDriven = 0;
double gallonsUsed = 0,
gasolineCost = 0;
int truckNumber,
numberOfTrips,
sumMilesDriven = 0;
double sumGallonsUsed = 0,
sumGasolineCost = 0;
int avgMilesDriven;
double avgGallonsUsed,
avgGasolineCost;
/* Display Truck Information
Get Number of Trips
Get Truck Information
Process Each Trip
Display Averages
*/
inputFile.open("100.txt");
//Display Truck Information
cout << " " << setw(35) << "Red-Rig Trucking" << endl << endl;
cout << " " << setw(40) << "Summary of Truck Operations" << endl << endl;
inputFile >> truckNumber;
cout << "Truck: " << truckNumber << endl << endl;
inputFile.close( );
inputFile.open("truck.txt");
//Get Number of Trips
inputFile >> numberOfTrips;
//Get Truck Information
cout << "Day" << " " <<setw(16) << "Miles" << " " << setw(16) << "Gallons"
<< " " << setw(16) << "Gasoline" << endl << setw(20) << "Driven" << " "
<< setw(16) << "Used" << " " << setw(16) << "Cost" << endl << endl;
while(!inputFile.eof()){
inputFile >> milesDriven >> gallonsUsed >> gasolineCost;
cout << x << " " << setw(17) << milesDriven << " " << setw(17)
<< fixed << setprecision(2) << gallonsUsed << " " << setw(12) << fixed
<< setprecision << gasolineCost << endl ;
x++;
}
//Process Each Trip
/*while(inputFile)
{ sumMilesDriven = sumMilesDriven + milesDriven;
inputFile >> milesDriven;
}*/
for (; milesDriven--;)
sumMilesDriven += milesDriven;
cout << endl << "Sum" << " " << setw(15) << sumMilesDriven ;
for (;gallonsUsed;)
sumGallonsUsed += gallonsUsed;
cout << " " << setw(17) << sumGallonsUsed;
for (;gasolineCost--;)
sumGasolineCost += gasolineCost;
inputFile.close( );
return 0;
}
I've gotten this far and I can't figure out what's wrong. I've taken out the milesDriven >=10 from the for loop parenthesis. When the code runs I get an incorrect sum amount. The sum is either too big or too small.
Your code:
for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);{
cout << " " << setw(17) << sumGasolineCost;
}
My first advice is, do not write confusing code. Whenever you're programming, you have better things to do than tie your shoelaces together. I think you know the above is equivalent to:
for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);
cout << " " << setw(17) << sumGasolineCost;
That lets us discuss the loop itself. Go back and consult your textbook. The for loop has three components:
for( init ; test ; incr )
init is executed once, usually to initialize what will be tested
test is executed on each iteration, including the first, to determine if the loop body will be executed
incr is executed after the loop body, usually to update the tested value
In your case, sumGasolineCost += gasolineCost is in init. It is executed once. It should be in the loop body. There are other errors, too. I can't be much more specific because you don't indicate where the array or input is that you're looping over.
Once you get your loop doing what it should, you might find the standard std::accumulate function interesting to compare to.

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