0

int x=10;
string y;

How do I bring about this conversion

y=x;

with a single statement? should I use typecasting, somebody pls guide me. I dont know how to do it.

itoa is so complex

3
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by phalaris_trip
0

>How do I bring about this conversion with a single statement?
The closest you'll get is Boost::lexical_cast. If you don't want to deal with Boost, it works something like this and the end result is a single statement:

#include <sstream>
#include <stdexcept>

template <typename To, typename From>
To lexical_cast ( const From &rhs )
{
  std::stringstream conv;
  To result;

  if ( !( conv<< rhs && conv>> result ) )
    throw std::runtime_error ( "Bad lexical_cast" );

  return result;
}

#include <iostream>
#include <string>

int main()
{
  int x = 10;
  std::string y;

  y = lexical_cast<std::string> ( x );

  std::cout<< y <<'\n';
}

>itoa is so complex
It's also not standard.

0
#include <iostream>
#include <string>
#include <sstream>

std::string int_to_string (int myInt)
{
    std::ostringstream s;
    s << myInt;
    return s.str();
}


int main() 
{
    int x = 10;
    std::string y;
    y = int_to_string(x);
    
    std::cout << y;
    std::cin.get();
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.