DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Convert String-Type The C++-Way

Snippets Manager user avatar by
Snippets Manager
·
Jan. 17, 07 · · Code Snippet
Like (0)
Save
Tweet
470 Views

Join the DZone community and get the full member experience.

Join For Free
A very useful snipped that converts strings to/from various types.

Here's the header:

#include 
#include 
#include 
#include 
#include 
using namespace std;

#ifndef ST_STRING
#define ST_STRING


enum CONVTYPE { STRTOINT, STRTOFLOAT, INTTOSTR, STRTODOUBLE }; 

/*
 *  Convtype converts an integer to a string and a string 
 *  string to an integer, a float, or a double. The third argument
 *  of this method determines what to do:
 *  STRTOINT, STRTOFLOAT, INTTOSTR, and STRTODOUBLE.
 *
 */
void convtype(void*, void*, const int& );  
  
#endif



The appropiate implementation:

void convtype(void* inp, void* out, const int& convtype)
{
  istringstream isbuf;
  ostringstream osbuf;

  switch(convtype)
    {
    case STRTOINT:
      isbuf.str(*(string*) inp);
      isbuf >> *((int*) out);
      break;
    case STRTOFLOAT:
      isbuf.str(*(string*) inp);
      isbuf >> *((float*) out);
      break;
    case STRTODOUBLE:
      isbuf.str(*(string*) inp);
      isbuf >> *((double*) out);
      break;
    case INTTOSTR:
      osbuf << *((int*) inp);
      *((string*)out)=osbuf.str();
      break;
    }
  return;
}
Convert (command)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Agile Coaches Without Technical Knowledge: How to Overcome the Paradox
  • Waterfall Vs. Agile Methodologies: Which Is Best For Project Management?
  • Exporting and Importing Projects in Eclipse
  • The Most Popular Technologies for Java Microservices Right Now

Comments

Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo