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 "stringstre am". 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<<e ndl; //***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***
} 5 2696
"cdg" <an****@anywher e.com> wrote in message
news:22rOf.1017 5$Tf3.784@duker ead09... 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 "stringstre am". 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<<e ndl; //***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?
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( ??? );
}
"cdg" <an****@anywher e.com> wrote in message
news:22rOf.1017 5$Tf3.784@duker ead09...
| 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 "stringstre am". 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<<e ndl; //***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.
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
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_li mits<int>::digi ts10
+ std::numeric_li mits<int>::is_s igned
+ 1 // for the most significant digit
+ 1 // for the trailing zero
];
std::snprintf(b uf, sizeof buf, "%d", ac);
} This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
(lex.literal). A string literal is an *lvalue*; all other literals are
*rvalues*.
-4- The operator :: followed by an identifier, a qualified-id, or an
operator-function-id is a primary-expression. Its type is specified by the
|
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.
|
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 = txtItemDesc.Text.ToCharArray
Dim pos As Integer
While pos < chrArr.Length
Dim c As Char
MsgBox(Asc(chrArr(pos)) & " " & chrArr(pos))
pos = pos + 1
|
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 this formatter writes into
a stream. And I am not used enough to C# to convert this to a string.
I tried the following code:
MemoryStream stream= new MemoryStream() ;
IFormatter formatter = new SoapFormatter();
|
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
s(i)=new string(test)
Above line gives - error implicit conversion string to 1-dim array of
| |
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 and resource
consuming Try... Catch, which in iterative processing is totally
unacceptable.
-tom
|
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 compression
string ->(Unicode Conversion) byte -(Compression + Unicode
Conversion) string
|
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++ code
(ie. wrappers etc). In Managed C++ there was an automatic conversion between
const char* and String^. This was useful to us for two reasons:
1. We declared our string constants as eg. const char* const c_My_Constant =
"blah", and these...
|
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 Unicode, UCS-2LE(BMP) in
Win32, and UCS4 in Linux?).
I have 2 ways to do the job:
|
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()
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
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...
| |
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
|
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...
| |