Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) CLN CLN example 2: basics: adding seperators to integers

 

 

CLN example 2 shows how to to convert an cln::cl_I to std::string and adding the thousands seperators.

 

Operating system: Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator 2.0.0

Project type: console application

Compiler: G++ 4.4.1

Libraries used:

 

 

 

 

 

Qt project file

 

#-------------------------------------------------
#
# Project created by QtCreator 2010-09-07T13:43:44
#
#-------------------------------------------------
QT       += core
QT       -= gui
LIBS += -L/usr/local/lib -lcln
TARGET = CppClnExample2
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

//---------------------------------------------------------------------------
#include <iostream>
#include <string>
//---------------------------------------------------------------------------
#include <boost/lexical_cast.hpp>
//---------------------------------------------------------------------------
#include <cln/cln.h>
//---------------------------------------------------------------------------
///IntToStrWithSep converts an integer to std::string
///and adds thousands seperators.
///From http://www.richelbilderbeek.nl/CppIntToStrWithSep.htm
const std::string IntToStrWithSep(cln::cl_I i)
{
  std::string s
    = boost::lexical_cast<std::string>(cln::mod(i,10));
  i = cln::floor1(i,10);
  int d = 1;
  while (!cln::zerop(i))
  {
    s = boost::lexical_cast<std::string>(cln::mod(i,10))
      + (d % 3 == 0 ? "," : "")
      + s;
    i = cln::floor1(i,10);
    ++d;
  }
  return s;
}
//---------------------------------------------------------------------------
int main()
{
  const cln::cl_I i("123456789012345678901234567890");
  std::cout << "i without seperators: " << i << '\n';
  const std::string s = IntToStrWithSep(i);
  std::cout << "i with seperators: " << s << '\n';
}
//---------------------------------------------------------------------------

 

Screen output:

 

i without seperators: 123456789012345678901234567890
i with seperators: 123,456,789,012,345,678,901,234,567,890

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict