473,398 Members | 2,393 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,398 software developers and data experts.

string conversion problem

cdg
Could anyone explain how to write this sample program correctly. I need to
convert an integer to a string. However, I would prefer to convert the
integer to char array. But I didn`t want to use "itoa".
And I am not that familar with using "stringstream". And is there better
approach to converting integers to char arrays.

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

char StringTest(int);

void main ()
{
int num = 123456789;
char num_ch = StringTest(num);
cout<<num_ch<<endl; //***this is to test print***
}

char StringTest(int num)
{
stringstream test;
test << num;
string int_str = test.str();

return int_str; //***needs to convert to char***
}
Mar 5 '06 #1
5 2681
"cdg" <an****@anywhere.com> wrote in message
news:22rOf.10175$Tf3.784@dukeread09...
Could anyone explain how to write this sample program correctly. I need
to
convert an integer to a string. However, I would prefer to convert the
integer to char array. But I didn`t want to use "itoa".
And I am not that familar with using "stringstream". And is there better
approach to converting integers to char arrays.

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

char StringTest(int);

void main ()
{
int num = 123456789;
char num_ch = StringTest(num);
cout<<num_ch<<endl; //***this is to test print***
}

char StringTest(int num)
{
stringstream test;
test << num;
string int_str = test.str();

return int_str; //***needs to convert to char***
}


Just have StringTest return a std::string and take the c_str() of it to
wherever you want it to go. Then you could even do:

char MyCStyleString[1000];

strcpy( MyCStyleString, StringTest(num).c_str() );

strcpy's 2nd parm is a const char*, which the c_str() gives you.

I would do it this way. Other's might save the results of StringTest to a
temp var then do the strcpy. Of course, if all you need is a const c-style
string that you'll not change, why not just leave it as std::string in a var
and use .c_str() when you need the c-style version?
Mar 5 '06 #2
cdg
In the program that I am writing, the integer that I need to convert to a
"char array" would not actually be a constant. So, how would I write the
code to save the results of StringTest to a temp variable. This is the where
I am having a problem.
And then I would need to either return the "temp var" or use "strcpy" in
the StringTest function, and return the char array. Either way would not be
a problem, but unfortunately I am not sure how to write most of this.

void main ( )
{
StringTest(num);
}

char StringTest(int num)
{
stringstream test;
test << num;
string int_str = test.str();

return( ??? );
}
Mar 5 '06 #3

"cdg" <an****@anywhere.com> wrote in message
news:22rOf.10175$Tf3.784@dukeread09...
| Could anyone explain how to write this sample program correctly. I need
to
| convert an integer to a string. However, I would prefer to convert the
| integer to char array. But I didn`t want to use "itoa".
| And I am not that familar with using "stringstream". And is there better
| approach to converting integers to char arrays.
|
| #include <iostream>
| #include <sstream>
| #include <string>
| using namespace std;
|
| char StringTest(int);
|
| void main ()
| {
| int num = 123456789;
| char num_ch = StringTest(num);
| cout<<num_ch<<endl; //***this is to test print***
| }
|
| char StringTest(int num)
| {
| stringstream test;
| test << num;
| string int_str = test.str();
|
| return int_str; //***needs to convert to char***
| }
|

A std::string is a container, a char is a primitive type. A pointer to char
may point to a single char or to an array of chars. Don't mix these. If you
have a std::string and you want a constant char* to it,
use c_str():

std::string s("my string");
char* p_s = s.c_str();

A std::string does not need a terminator. The result of what the statement
above generates is a distinct constant char array with a terminator at *p_s:

{'m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g', '0x0'}

Allow me to indulge in the topic a little.
A pointer's most important attribute is its type. A pointer to an integer is
not a pointer to an array of integers, etc. Typically, a pointer to a
container is what should be used instead.

The char* and const char* break that rule blatantly for historical
preservation of compatibility with C. A very unfortunate reality.

In the case of a std::string or any user-type, why deal with the uglyness
when you can simply pass a std::string* or better yet a reference to a
std::string:

void foo(const std::string& ref_s)
{
...
}

std::string n("my string");
foo(n);

Its much easier to program without pointers. In fact, the only reason to use
pointers at all in C++ is polymorphism allocations, functors along with a
few other exceptions.

Mar 5 '06 #4

cdg wrote:
In the program that I am writing, the integer that I need to convert to a
"char array" would not actually be a constant. So, how would I write the
code to save the results of StringTest to a temp variable. This is the where
I am having a problem.
And then I would need to either return the "temp var" or use "strcpy" in
the StringTest function, and return the char array. Either way would not be
a problem, but unfortunately I am not sure how to write most of this.
As Jim Langston said, return a std::string and convert to C-string
array-of-char at the last possible minute.

// You need a prototype for StringTest here.
void main ( ) main must return int, not void. {
StringTest(num); std::string s = StringTest(num); // Assuming num is an int with a valid
value. }

char StringTest(int num)
You're talking about returning a C-string but you've declared the
function to return a single char. Leave C-strings and pointers alone
until you absolutely can't avoid them.

std::string StringTest(int num)
{
stringstream test;
test << num;
return test.str();
}

This bit below can go. string int_str = test.str();

return( ??? );
}


The StringTest function is now responsible for converting an int to a
string. Elsewhere in your code, you can use the c_str() member function
of the std::string class if and when you really need a C-string.

Gavin Deane

Mar 5 '06 #5

cdg wrote:
Could anyone explain how to write this sample program correctly. I need to
convert an integer to a string. However, I would prefer to convert the
integer to char array. But I didn`t want to use "itoa".


Can you use snprintf?

#include <cstdio>
#include <limits>

int main(int ac, char** av)
{
char buf[
std::numeric_limits<int>::digits10
+ std::numeric_limits<int>::is_signed
+ 1 // for the most significant digit
+ 1 // for the trailing zero
];
std::snprintf(buf, sizeof buf, "%d", ac);
}

Mar 5 '06 #6

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

Similar topics

9
by: Steven T. Hatton | last post by:
This is from the draft of the previous version of the Standard: http://www.kuzbass.ru:8086/docs/isocpp/expr.html 2- A literal is a primary expression. Its type depends on its form...
9
by: Ronald Fischer | last post by:
Assume the following JavaScript function: function bracketize(s) { return ''; } This function which doesn't assume anything about its argument except that it must be convertible to a string.
7
by: john | last post by:
On my form i have a message box called txtItemDesc that displays the french phrase qualité Père Noël. Now then when i run this code on that text box: Dim chrArr() As Char chrArr =...
6
by: Marco Herrn | last post by:
Hi, I need to serialize an object into a string representation to store it into a database. So the SOAPFormatter seems to be the right formatter for this purpose. Now I have the problem that...
11
by: Zordiac | last post by:
How do I dynamically populate a string array? I hope there is something obvious that I'm missing here Option Strict On dim s() as string dim sTmp as string = "test" dim i as integer ...
6
by: tommaso.gastaldi | last post by:
Hi, does anybody know a speedy analog of IsNumeric() to check for strings/chars. I would like to check if an Object can be treated as a string before using a Cstr(), clearly avoiding the time...
5
by: jeremyje | last post by:
I'm writing some code that will convert a regular string to a byte for compression and then beable to convert that compressed string back into original form. Conceptually I have.... For...
3
by: Kevin Frey | last post by:
I am porting Managed C++ code from VS2003 to VS2005. Therefore adopting the new C++/CLI syntax rather than /clr:oldSyntax. Much of our managed code is concerned with interfacing to native C++...
10
by: Dancefire | last post by:
Hi, everyone, I'm writing a program using wstring(wchar_t) as internal string. The problem is raised when I convert the multibyte char set string with different encoding to wstring(which is...
21
by: phpCodeHead | last post by:
Code which should allow my constructor to accept arguments: <?php class Person { function __construct($name) { $this->name = $name; } function getName()
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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,...
0
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...

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.