Go back to Richel Bilderbeek's homepage.

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

 

 

 

(C++) CanCast

 

Checking code snippet that let you check if you can convert a std::string to another data type using LexicalCast.

 

CanCast serves the same purpose as CanLexicalCast, but does not throw an exception and does not use Boost. Note that there are differences between CanCast and CanLexicalCast, as CanLexicalCast is more strict. Below the code, a comparison between the two is shown

 

* View the code of 'CanCast' in plain text.

 

 

#include <string>

#include <sstream>

 

//From http://www.richelbilderbeek.nl/CppCanCast.htm

template <class TargetType> const bool CanCast(const std::string& from)

{

std::istringstream i(from);

TargetType temp;

return ( (i >> temp) ? true : false );

}

 

 

Comparison between CanCast and CanLexicalCast

 

The table below shows if a std::string can be converted according to CanCast (CC) and CanLexicalCast (CLC). Note that the first std::string was a space (' '). Below the table I show the code I've used to generate this output.

 

Type int int double double

string CC CLC CC CLC

false false false false

a false false false false

1 true true true true

1,1 true false true false

1.1 true false true true

1.1.1 true false true false

-1 true true true true

-1.1 true false true true

-1.1.1 true false true false

 

 

 

#include <vector>

 

int main()

{

std::vector<std::string> v;

v.push_back("");

v.push_back("a");

v.push_back("1");

v.push_back("1,1");

v.push_back("1.1");

v.push_back("1.1.1");

v.push_back("-1");

v.push_back("-1.1");

v.push_back("-1.1.1");

 

std::cout << "Type"

<< '\t' << "int"

<< '\t' << "int"

<< '\t' << "double"

<< '\t' << "double"

<< std::endl;

std::cout << "string"

<< '\t' << "CC"

<< '\t' << "CLC"

<< '\t' << "CC"

<< '\t' << "CLC"

<< std::endl;

 

std::cout << std::boolalpha;

 

const int size = v.size();

for (int i=0; i!=size; ++i)

{

std::cout << v[i]

<< '\t' << CanCast<int>(v[i])

<< '\t' << CanLexicalCast<int>(v[i])

<< '\t' << CanCast<double>(v[i])

<< '\t' << CanLexicalCast<double>(v[i])

<< std::endl;

}

}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.