Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mark-d-holmberg
Created March 9, 2011 18:56
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark-d-holmberg/862733 to your computer and use it in GitHub Desktop.
Save mark-d-holmberg/862733 to your computer and use it in GitHub Desktop.
convert a C++ std::string to the template type you specify
#include <iostream>
#include <string>
#include "sstreamconvert.h"
int main( int argc, char **argv ) {
//convert a string to a double
double D = convert_to <double>("13.37");
std::cout << "We can convert a string to a double using our neat template code" << std::endl;
std::cout << "The value of D is: [" << D << "]." << std::endl;
return 0;
}
all:
g++ -Wall -g -o sstream-convert.x86 main.cpp
clean:
rm sstream-convert.x86
#include <sstream>
#include <string>
template <typename T> T convert_to (const std::string &str)
{
std::istringstream ss(str);
T num;
ss >> num;
return num;
}
@tacshi
Copy link

tacshi commented Feb 21, 2017

You can take "12345.678" to have a try.

@oscarkramer
Copy link

Clever! I'm going to using it. It's such an easy solution instead of specialized templates. Thanks.

@mark-d-holmberg
Copy link
Author

Glad you like it.

@OwlCodR
Copy link

OwlCodR commented Aug 21, 2021

It's really interesing idea and it's so simple, thanks!

@Naptwen
Copy link

Naptwen commented Apr 14, 2022

Thank you, it is really helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment