Converting a numerical value to a string and vice-versa

amrith92 0 Tallied Votes 423 Views Share

These functions, to some, may seem trivial, but many people have queried in the forums on this topic numerous times.

The functions are templated, so that it can accommodate any data-type that the user wishes to use (For example, the same function can be used for converting variables of type long , int , double etc into strings, and vice-versa).

The first function, Fn I ( convertToString ), is capable of converting a variable of any data-type into a string.
Sample Function Call:

string MyInt = convertToString<int>(10);

The second function, Fn II ( convertFromString ), can convert a string into a variable of any data-type.
Sample Function Call:

int MyNumber = convertFromString<int>("45");

*Note*: You will have to include the header files - <sstream> and <string.h> for the code to work...

Hope this snippet helps....

/*
     This Function (Fn I) converts a variable of
     data-type DataType into a string
*/
template <typename DataType>
string convertToString(DataType MyValue)
{
     // Creates a Output String Stream to hold
     // the variable passed (MyValue)
     ostringstream OutStream;
    
     // Enter the variable into the stream
     OutStream << MyValue;
    
     // Return the stream as an array of
     // characters(string)
     return (OutStream.str());
}

/*
     This Function (Fn II) converts a string into
     a variable of data-type DataType
*/
template <typename DataType>
DataType convertFromString(string MyString)
{
     // Stores the return value
     DataType retValue;
    
     // Creates an Input String Stream to extract
     // the contents of the string
     istringstream InStream(MyString);
    
     // Read contents of String and store in retValue
     InStream >> retValue;
    
     // Return the value in the desired DataType
     return retValue;
}

Dani AI

Generated

Nice, clean starter from (and good catch from about using <string>). The template idea is fine for learning, but modern C++ gives simpler and/or faster choices depending on needs: convenience (C++11), robust validated parsing, and zero-allocation high-performance parsing (C++17). Use the simple APIs for quick work; use charconv (from_chars/to_chars) when you need speed and control. (de.cppreference.com)

Quick patterns (short, commonly useful):

#include <string>

std::string s = std::to_string(42);     // numeric -> string (C++11)
int n = std::stoi("42");                // string -> int (throws on error)
double x = std::stod("3.14");           // string -> double (throws on error)

std::to_string and the std::sto* family are fine for straightforward conversions, but note the sto* functions throw std::invalid_argument / std::out_of_range on bad input. (de.cppreference.com)

Safer / faster parsing (C++17): std::from_chars is non‑throwing, locale‑independent and non‑allocating. Use it when you need fast, validated parsing and check the returned .ec and that .ptr reached the end of the input to ensure the whole string parsed.

#include <charconv>
#include <optional>
#include <string_view>

std::optional<int> parse_int(std::string_view sv) {
    int v;
    auto res = std::from_chars(sv.data(), sv.data()+sv.size(), v);
    if (res.ec == std::errc{} && res.ptr == sv.data()+sv.size()) return v;
    return std::nullopt;
}

from_chars has strict rules (it does not skip leading whitespace; plus-sign handling differs for integers/floats), and floating-point overload support varied across library implementations — fallback to std::istringstream or std::strtod on older toolchains. When using std::istringstream, always check stream state and that no extra characters remain after extraction. (en.cppreference.com)

Summary: keep ’s idea (templates are useful), prefer std::to_string/std::sto* for quick code, and prefer std::from_chars/std::to_chars for production code that needs performance and strict validation — but handle library/version differences for floating-point carefully. (de.cppreference.com)

William Hemsworth 1,339 Posting Virtuoso

Good simple snippet :)

amrith92 119 Junior Poster

Thanks :)

tux4life 2,072 Postaholic

And it's well commented and it addresses a common beginner's problem :)
Though I'm not so sure about the <string.h> you've to include, it has to be <string>, contains several functions which operate on c-strings ...

Nice snippet!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.