473,795 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Storing byte stream in std::string

Hi,

I'm moving a socket library I wrote from C to C++. In the C version, I
had to malloc char arrays to store incoming communication. My hope was
to use std::string in C++, but then I realized a problem.

While '\0' is a valid string terminator for text, for my purposes it
is a problem. My program regularly gets '\0' as a value (Modbus/RTU
and TCP pass register values as the actual values, not the ASCII
chart). That would be a problem with std::string, I would think, since
it would see the '\0' as the end of a character stream, while, in
actuality, it would be all over the string and not indicate the
termination of the stream.

My question is whether I can write a stream of bytes to std::string,
read the length, and be able to get the whole string back. I expect
that I wouldn't be able to use any of the string functions, but could
I at least get the number of bytes store and get those bytes back at a
later time?

Or should I try a different container?

Thanks in advance,
T
Jan 3 '08 #1
5 7262
TBass wrote:
Hi,

I'm moving a socket library I wrote from C to C++. In the C version, I
had to malloc char arrays to store incoming communication. My hope was
to use std::string in C++, but then I realized a problem.

While '\0' is a valid string terminator for text, for my purposes it
is a problem. My program regularly gets '\0' as a value (Modbus/RTU
and TCP pass register values as the actual values, not the ASCII
chart). That would be a problem with std::string, I would think, since
it would see the '\0' as the end of a character stream, while, in
actuality, it would be all over the string and not indicate the
termination of the stream.
the representation of std::string doesn't treat '\0' a special
character, which means you an push_back any '\0' at any time.
>
My question is whether I can write a stream of bytes to std::string,
read the length, and be able to get the whole string back. I expect
that I wouldn't be able to use any of the string functions, but could
I at least get the number of bytes store and get those bytes back at a
later time?

Or should I try a different container?
Well, std::string does NOT guarantee the underlaying memory continuous.

I think std::vector is more like a buffer here, which guarantees
continuous underlying memory.

std::vector<cha rbuffer;
&buffer[0]; // get the pointer to the first cell.
Jan 3 '08 #2
std::vector<cha rbuffer;
&buffer[0]; // get the pointer to the first cell.
Great. I haven't messed with vector yet. I'll give that a try.
Jan 3 '08 #3
On Jan 3, 3:57 am, Barry <dhb2...@gmail. comwrote:

[...]
Well, std::string does NOT guarantee the underlaying memory
continuous.
It does in the most recent draft. Since the underlaying memory
is contiguous in all current implementations , and will be
guaranteed contiguous in the next version of the standard, I
think you can pretty much count on it.
I think std::vector is more like a buffer here, which guarantees
continuous underlying memory.
Conceptually, of course, I find std::vector< char a closer
fit. But both should work.
std::vector<cha rbuffer;
&buffer[0]; // get the pointer to the first cell.
You must "resize()" the container (std::string or std::vector)
to the target size before doing this.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jan 3 '08 #4
You must "resize()" the container (std::string or std::vector)
to the target size before doing this.
I did. I went right to vector as the solution, and it is working
nicely. Thank you!
Jan 3 '08 #5
TBass wrote:
>You must "resize()" the container (std::string or std::vector)
to the target size before doing this.

I did. I went right to vector as the solution, and it is working
nicely. Thank you!
It should work either in std::string or std::vector, but std::vector is
probably a better fit for binary date since you won't be using std::strings
string manilupating methods anyway.

In one implementation of a socket class I had done I had used std::string
and added each character
buffer += c;
with no problems.

That is one advantage to std::string, the syntax, rather than having to push
back
buffer.push_bac k(c);
but a small thing.

Either way, you should .reserve() before you start adding to either so the
string or vector won't have to keep resizing itself. Normally it's not much
of an issue but adding one character at a time can cause a large number of
resizes.
--
Jim Langston
ta*******@rocke tmail.com
Jan 4 '08 #6

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

Similar topics

10
8185
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
11
3662
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while( (idx=str.find_first_of(',')) >= 0 ) { str.replace( idx, 1, "" ); str.insert( idx, " or " ); }
22
13335
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; char c; std::string str;
19
6166
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not found anything). Here's the problem, I have two sets of files, the name of a file contains a number which is unique for each set but it's possible (even probable) that two files in different sets have the same numbers. I want to store these...
8
9202
by: Patrick Kowalzick | last post by:
Dear NG, I would like to change the allocator of e.g. all std::strings, without changing my code. Is there a portable solution to achieve this? The only nice solution I can think of, would be a namespace and another typedef to basic_string: namespace my_string {
6
11510
by: Nemok | last post by:
Hi, I am new to STD so I have some questions about std::string because I want use it in one of my projects instead of CString. 1. Is memory set dinamicaly (like CString), can I define for example string str1; as a class member and then add text to it. or do I have to specify it's length when defining? 2. How to convert from std::string to LPCSTR
2
5514
by: FBergemann | last post by:
if i compile following sample: #include <iostream> #include <string> int main(int argc, char **argv) { std::string test = "hallo9811111z"; std::string::size_type ret;
84
15906
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
1
2015
by: Slippy27 | last post by:
How do I test a byte string in Python? I want to manually convert (no libraries or functions) a UTF-8 string into UTF-16. My basic solution is to read from the stream some number of UTF-8 bytes, convert them into codepoints, then convert those codepoints into UTF-16 bytes. I want to code this myself, but I don't understand how to test the actual byte sequence. Let's say I use the following code to ensure I have a UTF-8 encoding (from Evan...
0
9673
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, 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...
0
9522
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
10443
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
10165
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
10002
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...
1
7543
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
6783
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
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2921
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.