473,387 Members | 1,489 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

typecast int to string

Hi All,

I want to typecast int to std::string how can i do it.

Here is the sample code.

int NewList[500];

//Fill the NewList with integers values.
.......
.......

//Replace the file contents with new list values at a specified location.

int i=0;
std::string line;
ifstream inFile(sample);//opens a file to read
while (getline (inFile, line) )
{

int comma1Pos = line.find(',');
int comma2Pos = line.find(',', comma1Pos+1);

int numChars = comma2Pos - comma1Pos - 1;

line.erase(comma1Pos+1, numChars); //
line.insert(comma1Pos+1, (std::string)NewList[i]);
i++;
}
inFile.close();

In the above code the function insert takes 2nd argument as a string so i
was trying to type cast NewList[i] to string.
The complier throws a type cast error saying type cast int to string is not
possible.

Is there any way i can type cast the same.
regards,
Venkat


Jul 22 '05 #1
9 11805
Try something like
int i=0;
std::string line;
ifstream inFile(sample);//opens a file to read
while (getline (inFile, line) )
{

int comma1Pos = line.find(',');
int comma2Pos = line.find(',', comma1Pos+1);

int numChars = comma2Pos - comma1Pos - 1;

line.erase(comma1Pos+1, numChars); // std::ostringstream os;
os << NewList[i];
line.insert(comma1Pos+1, os.str()); i++;
}
inFile.close();


--
To get my real email adress, remove the two onkas
--
Dipl.-Inform. Hendrik Belitz
Central Institute of Electronics
Research Center Juelich
Jul 22 '05 #2
On Wed, 07 Jan 2004 19:39:14 +0530, Venkat wrote:
Hi All,

I want to typecast int to std::string how can i do it.

Here is the sample code.

int NewList[500];

//Fill the NewList with integers values.
......
......

//Replace the file contents with new list values at a specified location.

int i=0;
std::string line;
ifstream inFile(sample);//opens a file to read
while (getline (inFile, line) )
{

int comma1Pos = line.find(',');
int comma2Pos = line.find(',', comma1Pos+1);

int numChars = comma2Pos - comma1Pos - 1;

line.erase(comma1Pos+1, numChars); //
line.insert(comma1Pos+1, (std::string)NewList[i]);
i++;
}
inFile.close();

In the above code the function insert takes 2nd argument as a string so i
was trying to type cast NewList[i] to string.
The complier throws a type cast error saying type cast int to string is not
possible.

Is there any way i can type cast the same.


No, that is not what casting is about. Casting can change something to
something related. Although for humans integers and their
string-representations may be related, for computers they are very
different.

As a side note, you should never use C-style casts in C++, C++ has much
better casts: static_cast<>, dynamic_cast<>, const_cast<> and
reinterpret_cast<>. Familiarize yourself with those and never use the
C-style casts again. It will save you a lot of grief.

So the question now becomes, how to convert a number to a string. Thee are
a number of ways to do so, the easiest and most C++ish:

#include <sstream>

std::string toString(int i)
{
std::stringstream s;
s << i;
return s.c_str();
}

OK, this works, but maybe you want to use this for unsigned ints as well.
Or for longs. You could create the same function multiple times,
overloading on the argument:

std::string toString(long) { ... }
std::string toString(unsigned int) { ... }
std::string toString(unsigned long) { ... }
std::string toString(float) { ... }
std::string toString(double) { ... }

Fortunately, there is an easier way. We can get the compiler to do it for
us by using the magic of templates:

template<typename T>
std::string toString(T t)
{
std::stringstream s;
s << t;
return s.c_str();
}

This will make the compiler produce all of the above functions
automagically, but only the ones we actually use! (Do note that this code
must be 'seen' by the compiler before you use it, you cannot just use a
prototype and define the function in another C++ file. So this typically
goes in some header.)

So if you use toString(i), where i is an integer, the compiler will
substitute int for T and we end up with exectly the same as above. But if
we use toString(l), where l is a long, the compiler automagically
generates the above for a long. Templates can be so incredibly powerful!

HTH,
M4
Jul 22 '05 #3
Venkat,

Probably, you want to try looking at Boost's lexical cast facility. The
boost designers (a free add on to the STL) have provided save means to
do what you are asking. so see an example, take a look at

http://www.boost.org/libs/conversion/lexical_cast.htm

Evan Carew

Venkat wrote:
Hi All,

I want to typecast int to std::string how can i do it.

Here is the sample code.

int NewList[500];

//Fill the NewList with integers values.
......
......

//Replace the file contents with new list values at a specified location.

int i=0;
std::string line;
ifstream inFile(sample);//opens a file to read
while (getline (inFile, line) )
{

int comma1Pos = line.find(',');
int comma2Pos = line.find(',', comma1Pos+1);

int numChars = comma2Pos - comma1Pos - 1;

line.erase(comma1Pos+1, numChars); //
line.insert(comma1Pos+1, (std::string)NewList[i]);
i++;
}
inFile.close();

In the above code the function insert takes 2nd argument as a string so i
was trying to type cast NewList[i] to string.
The complier throws a type cast error saying type cast int to string is not
possible.

Is there any way i can type cast the same.
regards,
Venkat


Jul 22 '05 #4
[Snip]
#include <sstream>

std::string toString(int i)
{
std::stringstream s;
s << i;
return s.c_str();
}

Shouldn't "std::stringstream s" be "std::ostringstream s"? Which one is better? Why?

--The Directive
OK, this works, but maybe you want to use this for unsigned ints as well.
Or for longs. You could create the same function multiple times,
overloading on the argument:

std::string toString(long) { ... }
std::string toString(unsigned int) { ... }
std::string toString(unsigned long) { ... }
std::string toString(float) { ... }
std::string toString(double) { ... }

Fortunately, there is an easier way. We can get the compiler to do it for
us by using the magic of templates:

template<typename T>
std::string toString(T t)
{
std::stringstream s;
s << t;
return s.c_str();
}

This will make the compiler produce all of the above functions
automagically, but only the ones we actually use! (Do note that this code
must be 'seen' by the compiler before you use it, you cannot just use a
prototype and define the function in another C++ file. So this typically
goes in some header.)

So if you use toString(i), where i is an integer, the compiler will
substitute int for T and we end up with exectly the same as above. But if
we use toString(l), where l is a long, the compiler automagically
generates the above for a long. Templates can be so incredibly powerful!

HTH,
M4

Jul 22 '05 #5
On Wed, 07 Jan 2004 18:37:07 -0800, The Directive wrote:
[Snip]
#include <sstream>

std::string toString(int i)
{
std::stringstream s;
s << i;
return s.c_str();
}

Shouldn't "std::stringstream s" be "std::ostringstream s"? Which one is
better? Why?


Yes.. Somehow I have a problem remembering which stringstream to use,
while I now find it obvious. I thought about it, but did not want any risk
of getting it wrong. Stupid of me really.

M4
Jul 22 '05 #6
Martijn Lievaart wrote:
On Wed, 07 Jan 2004 18:37:07 -0800, The Directive wrote:
[Snip]
#include <sstream>

std::string toString(int i)
{
std::stringstream s;
s << i;
return s.c_str();
}

Shouldn't "std::stringstream s" be "std::ostringstream s"? Which one
is better? Why?


Yes.. Somehow I have a problem remembering which stringstream to use,
while I now find it obvious. I thought about it, but did not want any
risk of getting it wrong. Stupid of me really.


I was always wondering why there is an istringstream and an
ostringstream if a stringstream already does what both can do. So
what's the actual advantage of using an ostringstream over a
stringstream?

Jul 22 '05 #7
On Thu, 08 Jan 2004 10:48:40 +0100, Rolf Magnus wrote:
I was always wondering why there is an istringstream and an
ostringstream if a stringstream already does what both can do. So
what's the actual advantage of using an ostringstream over a
stringstream?


I'm guessing, efficiency. An istream and an ostream both need to maintain
state, so you'll shave of a few bytes and operations by using the best
suitable class.

Also, on implementations that link complete objects (I guess most
implementations do this), as opposed to linking only the parts of an
object you need, you might link in much more than you actually need.

HTH,
M4

Jul 22 '05 #8
Martijn Lievaart <m@remove.this.part.rtij.nl> wrote in message news:<pa****************************@remove.this.p art.rtij.nl>...
On Wed, 07 Jan 2004 19:39:14 +0530, Venkat wrote:
<snip>
template<typename T>
std::string toString(T t)
{
std::stringstream s;
s << t;
return s.c_str();
ITYM
return s.str();
}


--
GJD
Jul 22 '05 #9
On Thu, 08 Jan 2004 04:26:12 -0800, Gavin Deane wrote:
Martijn Lievaart <m@remove.this.part.rtij.nl> wrote in message
news:<pa****************************@remove.this.p art.rtij.nl>...
On Wed, 07 Jan 2004 19:39:14 +0530, Venkat wrote:


<snip>
template<typename T>
std::string toString(T t)
{
std::stringstream s;
s << t;
return s.c_str();


ITYM
return s.str();
}


Yup, thanks.

M4
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Lars Plessmann | last post by:
I have a problem with typecast methods. Here is a setter of an object: function setKind($kind) { if (is_int((int)$kind) and (strlen($kind)<=6)) { $this->kind = $kind; return true;
1
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen...
1
by: nsj | last post by:
How to typecast double into ascii or string? Please help me.
8
by: akolsen | last post by:
Hello there. This should be simple, but im having trouble anyway of getting it to work. I have a boxed object that i want to cast to its native type, but I would like to use reflection to do...
11
by: Manikandan | last post by:
Hi, I am using the following snippet to compare an object with integer in my script. if ( $forecast < 4 ) { I got the "segmentation fault" error message when i executed this script in CLI....
5
by: SunnyDrake | last post by:
HI! I wrting some program part of it is XML config parser which contains some commands(for flexibility of engenie). how do i more simple(if it possible not via System.Reflection or...
3
by: ryan.gilfether | last post by:
I have a problem that I have been fighting for a while and haven't found a good solution for. Forgive me, but my C++ is really rusty. I have a custom config file class: class ConfigFileValue...
1
by: niharnayak2003 | last post by:
Hi All, I am facing the problem in Typecast inside the Generic class. I need a function which will take two param 1:-Xpath 2:- XMLDOC and return me what i will need. here is the code for...
0
by: Paulson | last post by:
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go -- ============================================= -- Author: Lokesh Rao V.L -- Create date: 18 June 2007 -- Description: Adds, updates...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.