473,726 Members | 2,177 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(comm a1Pos+1, numChars); //
line.insert(com ma1Pos+1, (std::string)Ne wList[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 11831
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(comm a1Pos+1, numChars); // std::ostringstr eam os;
os << NewList[i];
line.insert(com ma1Pos+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(comm a1Pos+1, numChars); //
line.insert(com ma1Pos+1, (std::string)Ne wList[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_cas t<>. 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::stringstre am 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(unsign ed int) { ... }
std::string toString(unsign ed 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<typena me T>
std::string toString(T t)
{
std::stringstre am 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(comm a1Pos+1, numChars); //
line.insert(com ma1Pos+1, (std::string)Ne wList[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::stringstre am s;
s << i;
return s.c_str();
}

Shouldn't "std::stringstr eam s" be "std::ostringst ream 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(unsign ed int) { ... }
std::string toString(unsign ed 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<typena me T>
std::string toString(T t)
{
std::stringstre am 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::stringstre am s;
s << i;
return s.c_str();
}

Shouldn't "std::stringstr eam s" be "std::ostringst ream 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::stringstre am s;
s << i;
return s.c_str();
}

Shouldn't "std::stringstr eam s" be "std::ostringst ream 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.t his.part.rtij.n l>...
On Wed, 07 Jan 2004 19:39:14 +0530, Venkat wrote:
<snip>
template<typena me T>
std::string toString(T t)
{
std::stringstre am 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.t his.part.rtij.n l>...
On Wed, 07 Jan 2004 19:39:14 +0530, Venkat wrote:


<snip>
template<typena me T>
std::string toString(T t)
{
std::stringstre am 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
2092
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
2225
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 pertaining to casting class A to class B, the implementation of the
1
1312
by: nsj | last post by:
How to typecast double into ascii or string? Please help me.
8
4234
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 the typecasting. This is the regular way.
11
1929
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. After debugging, i had changed my code to
5
2311
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 System.CodeDom.CodeCastExpression) __problem typecast #1 Desc:i do needed checks but data/commands in XML is dynamic and i don't wanna fix C# code again and again... Sample:foreach (object some in somearray) (some.GetType())some.someaction();
3
4086
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 { public: operator string(); // allow this class to be typecast into a string operator char*(); // allow this class to be typecast into a char*
1
8198
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 accessing to the Generic class. private double mtrxgraphdata; private XMLdocument Matrixdata;
0
787
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 LogCompliance details. -- =============================================
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8101
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.