You are here:

C++/Char and int

Advertisement


Question
Hi.
I wonder if theres possible to add a int variable to a char string.

For example:
int x=5;
char c[16];
c="{" << x << ";" << x+1 << "}";

so that c would look like {5;6}?

Answer
Yes there is. But it is not done quite how you show. However you are very nearly there: you are correct in that the key is to use the stream insertion operators, operator<<. However rather than using straight assignment we need to use an output stream, a std::ostream object type.

But, I here you say, surly such streams are for writing to the console or to files? Yes indeed. However the standard C++ library also has stream types for outputting to (and inputting from) memory: that is to strings in memory, which is what you are attempting to do here.

There are two output stream types in the standard C++ library for writing to strings: one that writes to a std::string and the other (that has a counterpart in pre-standard C++) that writes to a C-style char array buffer as you are using here.

To write to a char array buffer we can do the following:

   #include <strstream>

   // ...

   std::ostrstream ostrm;

   ostrm << "{" << x << ";" << x+1 << "}" << std::ends;

   char * theString = ostrm.str();
   std::cout << theString;
   

Things to note are:

- That the char buffer array is dynamically allocated by
 std::ostrstream in this mode. Asking for a pointer to the buffer, as
 I do at the end for theString, causes the buffer to be frozen
 meaning it cannot be manipulated and thus will not be re-allocated
 out from under external references such as theString. To un-freeze
 the buffer you pass false to the freeze member function:

   ostrm.freeze( false );

- That you need to terminate the C-string using std::ends.

- That you can also use a fixed buffer std::ostrstream which it is
 passed during construction:

   size_t const BufferSize(16);

   char c[BufferSize]; // Store up to 15 characters + zero terminator

   std::ostrstream ostrm( c, BufferSize ); // use fixed size buffer

   ostrm << "{" << x << ";" << x+1 << "}" << std::ends;

   std::cout << c;

In this case the std::ostrstream instance is never responsible for the management of the buffer and will never resize and reallocate it. Thus there is no need to use freeze and that you have to ensure that the data you write into the buffer does not exceed the length of the buffer. In fact such attempts should fail and put the stream into a bad (fatal error) state.

Note that support in standard C++ for the C-style char * streams (ostrstream and istrstream) are deemed as compatibility features and marked as depreciated. Some compilers may give a warning about using deprecated features.

The alternative is to use the standard C++ library std::string type to hold the string data rather than a C-style, raw, fixed size array of char that is zero terminated. In this case we include sstream and use std::ostringstream:

   #include <sstream>

   // ...

   std::ostringstream os;

   os << "{" << x << ";" << x+1 << "}";

   std::cout << os.str(); // Write std::string buffer to std::cout

If you really need to access the std::string data as a C-style string (maybe to pass it to some function that takes a const char * ), then we can call c_str() on the std::string reference returned by the std::ostringstream::str() operation:

   printf( os.str().c_str() )

Note that the std::string object internal to std::ostringstream objects is responsible for the management of the string character storage. Thus there is no freeze equivalent for std::ostringstream. Often the safest approach if you are re-using a std::ostringstream object is to copy its data when needed to completely separate std::string objects:

   std::string intPairStr( os.str() );

I should note that you can of course use all the C++ IOStream formatting facilities when using the string stream types, as well as other stream operations such as unformatted output (put, write) and stream positioning such as seekp. And of course you can use values of any type that has operator<< support (or operator>> for the input string streams), not just integer types.

Hope this is of help.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.