Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Convert String-Type The C++-Way

DZone's Guide to

Convert String-Type The C++-Way

·
Free Resource
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;
}
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}