My project is to create this output using setw(), setfill(), setiosflags():
Enter KWH used 993
C O M P S C I Electric
------------------------------------------------
Kilowatts Used 993
------------------------------------------------
Base Rate 993 @ $ 0.0475 $ 47.17
Surcharge $ 4.72
Citytax $ 1.42
______
Pay this amount $ 53.31
After May 20th Pay $ 55.44
I can get this to work using my code, but only if Kilowatts used is 2 digits. If it is more digits, my right justify does not work. I can edit the code so it justifies correctly for 3 digits, 4 digits, and so on. When my code will be test, I do not know what Kilowatts would be inputted, so I need code that works for Kilowatts with any length of digits.
/*
* File: main.cpp
* Author: -------------------------
*
* Created on ----------------------
*/
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
/*
*
*/
int main() {
float br; // base rate
float surcharge; // surcharge
float taxrate; // tax rate
float late; // late rate
float kwh; // kilowatts used
float bc; // base cost
float scc; // surcharge cost
float ctc; // city tax cost
br = .0475; // kilowatt rate
surcharge = .1; // surcharge rate
taxrate = .03; // tax rate
late = .04; //rate if payment is late
// cout.width(38);
cout << "Kilowatts used last month: ";
cin >> kwh; // get kwh used from user
cout << "\n";
cout << "\n";
cout << " C O M P S C I Electric " << "\n";
cout << setiosflags(ios::fixed|ios::showpoint) << setprecision(2); // set ios flags
cout << setfill('-') << setw(38) << "\n"; // display dashes in line
cout << setiosflags(ios::left) << "Kilowatts Used" << setfill(' ') << setw(23) << resetiosflags(ios::left) << kwh << "\n"; // output kwh formally
cout << setfill('-') << setw(38); // separate
cout << "\n" << "\n";
// calculations
bc = br * kwh;
scc = surcharge * kwh;
ctc = taxrate * kwh;
cout << left << "Base Rate " << kwh << " @ $0.0475 " << setfill(' ') << setw(4) << right << "$" << bc << "\n"; //output base rate, right justify cost
cout << left << "Surcharge" << setw(24) << right << "$" << scc << "\n"; // output surcharge cost, right justify cost
return 0;
}
I don't understand the need for setw()
when I use resetiosflags(ios::left)
to right justify. I tried replacing setiosflags(ios::left)
and resetiosflags(ios::left)
with the right
and left
;
I am a c++ beginner using netbeans c++ to code and g++ to compile. I really don't know much about formatting console output much, so I would appreciate any help. I don't necessarily have to use the 3 functions specified at the top, as long as a different way works consisently with any float length. Thanks!