i wanna know how to set an certain number with commas, for instance

if i had this

#include <iostream>
#include <iomanip>
using namespace std; 

int main()
{


int numItems;
double total;
const double costOfItems = 1050;
cout << "enter number of items ";
cin >> numItems;

total = costOfItems * numItems;
cout << total;
}

how would i set 4200 output as 4,200

Recommended Answers

All 3 Replies

convert to string then insert the commas

#include <sstream>
#include <string>
using namespace sd;

int main()
{
    int n = 4200;
    stringstream stream;
    stream << n;
    string str;
    stream >> str;
    // now insert the commas in the appropirate spot
    // I'll leave that up to you to figure out.
}

Here's a method that definitely can't be turned in as homework:

#include <iostream>
#include <locale>
#include <string>

template <typename CharT>
class numfmt: public std::numpunct<CharT> {
  CharT _thousands_sep;
  int _grouping;
public:
  numfmt ( CharT thousands_sep, int grouping )
    : _thousands_sep ( thousands_sep ), _grouping ( grouping )
  {}
private:
  CharT do_thousands_sep() const
  {
    return _thousands_sep;
  }

  std::string do_grouping() const
  {
    return std::string ( 1, _grouping );
  }
};

int main()
{
  numfmt<char> *comma_value = new numfmt<char> ( ',', 3 );
  
  std::cout.imbue ( std::locale ( std::locale(), comma_value ) );

  for ( long int n = 0, i = 1; n < 10; n++, i *= 10 )
    std::cout<< i <<'\n';
}

What a wonderful demonstration of the tremendous flexibility of the language. I'm equally impressed by the command of language necessary to create the demonstration. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.