cout with setw ?

T

tvn007

Below is my code:

#include <string>
#include <iostream>
#include <iomanip>
int main (void){
using namespace std;

string name1 = "JOHN";
int id1 = 1234;
float balance1 = 27000.00;
float available1 = 14000.00;
cout
<<left<<setw(20)<<"NAME"<<setw(20)<<"ID"<<setw(20)<<"BALANCE"<<setw(20)<<"AVAILABLE"<<endl;
cout
<<left<<setw(20)<<name1<<setw(20)<<id1<<setw(20)<<setprecision(15)<<balance1<<setw(20)<<available1<<endl;
}
output:

NAME ID BALANCE AVAILABLE
JOHN 1234 27000 14000

however, I would like to have the output as follow:

NAME ID BALANCE AVAILABLE
JOHN 1234 27000.00Cents 14000.00Cents

Thanks in advance for any hints.
 
M

Mike Wahler

Below is my code:

#include <string>
#include <iostream>
#include <iomanip>
int main (void){
using namespace std;

string name1 = "JOHN";
int id1 = 1234;
float balance1 = 27000.00;
float available1 = 14000.00;
cout
<<left<<setw(20)<<"NAME"<<setw(20)<<"ID"<<setw(20)<<"BALANCE"<<setw(20)<<"AVAILABLE"<<endl;
cout
<<left<<setw(20)<<name1<<setw(20)<<id1<<setw(20)<<setprecision(15)<<balance1<<setw(20)<<available1<<endl;
}
output:

NAME ID BALANCE AVAILABLE
JOHN 1234 27000 14000

however, I would like to have the output as follow:

NAME ID BALANCE AVAILABLE
JOHN 1234 27000.00Cents 14000.00Cents

Thanks in advance for any hints.

stringstreams are useful for "pre-building" formatted strings:

#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>

int main()
{
double value(27000);

std::eek:stringstream oss;
oss << std::setprecision(2) << std::fixed;
oss << value << "Cents";

std::cout << std::left;
std::cout << std::setw(20) << "BALANCE" << '\n';
std::cout << std::setw(20) << oss.str() << '\n';
return 0;
}

Output:

BALANCE
27000.00Cents


-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top