473,594 Members | 2,756 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on converting unsigned long to std::string

Hi,

I need to convert unsigned long data to a std::string, I googled a bit
to see if the string class supports any methods to achieve this - but
didnt find any, I think of using sprintf and converting to a char buf
and then putting it back in std::string -

is anyone aware of any other way?

Thanks
/R
Oct 10 '08 #1
4 6494
On Thu, 09 Oct 2008 21:12:51 -0700, Ramesh wrote:
Hi,

I need to convert unsigned long data to a std::string, I googled a bit
to see if the string class supports any methods to achieve this - but
didnt find any, I think of using sprintf and converting to a char buf
and then putting it back in std::string -

is anyone aware of any other way?

Thanks
/R
istringstream is one way without resorting to the C libraries

see this example

http://www.nylxs.com/docs/workshops/pharm.C.html

look around line 670
668 float Weight::wgt(con st string &descr)
669 {
670 string errormsg("ERROR : enter a number followed by either \"kilograms\ " or \"pounds\"") ;
671 istringstream stream1;
672 stream1.str(des cr);
673 if (!(stream1>>wgt _))
674 throw errormsg;
675 if(!(stream1>>u nit_))
676 throw errormsg;
677 errormsg = "ERROR: enter either \"kilograms\ " or \"pounds\"";
678 if( unit_ == "kg" || unit_ == "k" || unit_ == "kilo" || unit_ == "kilogram"| | unit_ == "kilograms" ){
679 unit_ = "kg";
680 }else if( unit_ == "lb" || unit_ == "pound" || unit_ == "pd"|| unit_ == "pounds" ){
681 wgt_ = wgt_ * 0.45454545;
682 }else{
683 throw errormsg;
684 }
685 return wgt_;
686 }
687

--
http://www.mrbrklyn.com - Interesting Stuff
http://www.nylxs.com - Leadership Development in Free Software

So many immigrant groups have swept through our town that Brooklyn, like Atlantis, reaches mythological proportions in the mind of the world - RI Safir 1998

http://fairuse.nylxs.com DRM is THEFT - We are the STAKEHOLDERS - RI Safir 2002

"Yeah - I write Free Software...so SUE ME"

"The tremendous problem we face is that we are becoming sharecroppers to our own cultural heritage -- we need the ability to participate in our own society."

"I'm an engineer. I choose the best tool for the job, politics be damned.<
You must be a stupid engineer then, because politcs and technology have been attached at the hip since the 1st dynasty in Ancient Egypt. I guess you missed that one."

© Copyright for the Digital Millennium

Oct 10 '08 #2
On Oct 10, 6:23 am, Ruben <ru...@www2.mrb rklyn.comwrote:
istringstream is one way without resorting to the C libraries
Since he wants to convert a number to a string, I'd rather use
ostringstream. An example can be found at:

http://www.parashift.com/c++-faq-lit....html#faq-39.1

-- Daniel
Oct 10 '08 #3
Ramesh wrote:
Hi,

I need to convert unsigned long data to a std::string, I googled a bit
to see if the string class supports any methods to achieve this - but
didnt find any, I think of using sprintf and converting to a char buf
and then putting it back in std::string -

is anyone aware of any other way?
If you are used to sprintf but want something that deals with std::string
instead, you could try this:

bool strprintf ( std::string & buffer, char const * format, ... ) {
while ( true ) {
buffer.resize( buffer.capacity () );
int old_length = buffer.size();
std::va_list aq;
va_start( aq, format );
int length_needed =
vsnprintf( &buffer[0], old_length + 1, format, aq );
va_end( aq );
if ( length_needed < 0 ) {
return ( false );
}
buffer.resize( length_needed );
if ( length_needed <= old_length ) {
return ( true );
}
}
}
WARNING: the above is not standard compliant; it assumes that std::string is
contiguous (as far as I know, all implementations are, and it will be
required by the next iteration of the standard C++0X); also it requires
that is is legal to write a trailing 0 behind the string. Also, it assumes
that vsnprintf() conforms to C99 or C++0X. Thus, you have to test this
carefully.
Best

Kai-Uwe Bux
Oct 10 '08 #4
Ramesh wrote:
is anyone aware of any other way?
I really can't understand why two people have already answered your
question with overly long and complicated answers, which are also
basically just wrong. Come on, people, keep answers simple and
concentrate on the *basics*.

What you want is this:

std::ostringstr eam os;
os << yourUnsignedVal ue;
std::string theValueAsStrin g = os.str();
Oct 10 '08 #5

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

Similar topics

1
12259
by: red floyd | last post by:
I have a an app that I'm writing which uses char and std::string. I'm using a library which expects wchar_t arrays. Is there a standard way to convert between std::string and std::wstring, or do I need to use something like std::transform()? Thanks
13
2478
by: Gil | last post by:
I have a string : string A = "2"; I need to get it's integer value : // ?? int val = A ; // ??
7
117990
by: AlexFarokhyans | last post by:
Hello, I'm trying to convert String to Char array. I'm getting a string from user input text box and then I have char firstName. I need to convert the string that is in the text box to firstName. Thank you
5
15900
by: Torben Laursen | last post by:
Hi Can anyone show me how to convert between VARIANT and std::string and back, thanks! Torben ---
2
4801
by: zhege | last post by:
I am a beginner of C++; I have a question about the std:string and std:cout class; Two pieces of code: -------------------------------- #include <iostream> #include <string> using namespace std; int main()
1
1720
by: zhege | last post by:
I am a beginner of C++; I have a question about the std:string and std:cout class; Two pieces of code: -------------------------------- #include <iostream> #include <string> using namespace std; int main()
2
10870
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to think for a sec. At first I read it as converting a 'const char *' to a 'std::string *' void f(const std::string &s) { std::cout << s.size() << "\n";
2
3085
by: =?Utf-8?B?QWJoaW1hbnl1IFNpcm9oaQ==?= | last post by:
Hi, I am using Visual C++ in Visual Studio 2005 to create a Managed Wrapper around some C++ LIBS. I've created some classes that contains a pointer to the LIB classes and everthing seems to compile well. The problem is getting a std::string from System::String and still preserving the nulls. System::String is a base64 encoded string of a series of bytes. When I convert it back to a string from base64 representation, the NULLs inside the...
12
1760
by: manishsharma1 | last post by:
Hi, I have one long String like this: 015EnvironmentData1........ I want to read first three character from it and convert them to integer. This will be the length of the Name of the field and then there is value. So if we take above example
0
7876
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
8251
Oralloy
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...
1
8003
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,...
0
8234
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
6654
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
5739
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
3897
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2385
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
0
1210
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.