473,614 Members | 2,101 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

add a null to a std::string.

I need to make a class called uid.
A UID is a unique identifier.
It looks like... 1.2.3.345.1.2.4 .566
This uid get transmitted over a network as 8 bit binary data.
If the length of the UID is odd, an extra padding null \0 is added
to the end.

This is what I've written but I'm not sure if I've garanteed to have
the c_str() method return a buffer that is null padded.
class uid
{
private:
std::string id;
public:
uid(std::string _id)
{
id = _id;
unsigned int len = id.size();
if (len & 0x00000001)
id.push_back(0x 00);
}
int getSize(void)
{
return id.size();
}
const void *getData(void)
{
return id.c_str();
}
};

Feb 24 '06 #1
7 11584
JustSomeGuy wrote:
This is what I've written but I'm not sure if I've garanteed to have
the c_str() method return a buffer that is null padded.


The method 'c_str()' will return a pointer to a null-terminated
representation of the 'std::string's content. That is, you will
have an extra null-character tagged on to the 'std::string's
content. If the 'std::string's content contains null-characters,
you cannot process the result of 'c_str()' with the 'str...()'
functions because these might stop at the first embedded
null-character. Thus, you probably should use the 'data()' method
instead because this has the same effect as 'c_str()' except that
it does not add an extra null-character.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Feb 24 '06 #2

Dietmar Kuehl wrote:
JustSomeGuy wrote:
This is what I've written but I'm not sure if I've garanteed to have
the c_str() method return a buffer that is null padded.


The method 'c_str()' will return a pointer to a null-terminated
representation of the 'std::string's content. That is, you will
have an extra null-character tagged on to the 'std::string's
content. If the 'std::string's content contains null-characters,
you cannot process the result of 'c_str()' with the 'str...()'
functions because these might stop at the first embedded
null-character. Thus, you probably should use the 'data()' method
instead because this has the same effect as 'c_str()' except that
it does not add an extra null-character.


Actually c_str would work in this guy's case. He wants to output the 0
under certain circumstances. So he should be able to just grab c_str
and output +/- 1 byte depending on conditions.

Feb 24 '06 #3
Thank you for your reply.
Thinking about it I realised that if the getSize method is changed such
that
the length returned is rounded up to the nearest even number then the
data
returned by getData will included the null, because the c_str method
points
to a null terminated string anyways...

Feb 24 '06 #4
ro**********@gm ail.com wrote:
Actually c_str would work in this guy's case.
I never claimed it doesn't. The way he inserts the null manually,
he can, however, also use 'data()' ... and it would be clearer
that the result is not intended for consumption by the 'str...()'
functions.
He wants to output the 0
under certain circumstances. So he should be able to just grab c_str
and output +/- 1 byte depending on conditions.


Yes, this would be an approach avoiding the need to manually attach
the null character.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Feb 24 '06 #5
Dietmar Kuehl a écrit :

Thus, you probably should use the 'data()' method
instead because this has the same effect as 'c_str()' except that
it does not add an extra null-character.


Well actually, data() and c_str() are the same on some implementations
(like GNU libstdc++)
Using data() instead of c_str() may prevent a copy though.
Feb 24 '06 #6
In article <46************ @individual.net >,
Dietmar Kuehl <di***********@ yahoo.com> wrote:
JustSomeGuy wrote:
This is what I've written but I'm not sure if I've garanteed to have
the c_str() method return a buffer that is null padded.


The method 'c_str()' will return a pointer to a null-terminated
representation of the 'std::string's content. That is, you will
have an extra null-character tagged on to the 'std::string's
content. If the 'std::string's content contains null-characters,
you cannot process the result of 'c_str()' with the 'str...()'
functions because these might stop at the first embedded
null-character. Thus, you probably should use the 'data()' method
instead because this has the same effect as 'c_str()' except that
it does not add an extra null-character.


Let's say I have a string class that doesn't hold its data in a
contiguous array but still wants to conform to the standard. This would
mean I have to create an array and fill it whenever c_str is called (and
I'm free to delete it whenever a non-const member-function is called.)

Would my class be standard conforming if I only made a c_str array up to
the first null? (I expect that data would have to have all the
characters.)

In other words given:

int main()
{
std::string s = "Hello! World";
s[6] = 0;
const char* foo = s.c_str();
char bar[6];
std::strcpy( bar, foo + 7 );
std::cout << bar;
}

Does the standard define the output of the above program?
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Feb 24 '06 #7
Daniel T. wrote:
In article <46************ @individual.net >,
Dietmar Kuehl <di***********@ yahoo.com> wrote:
JustSomeGuy wrote:
> This is what I've written but I'm not sure if I've garanteed to have
> the c_str() method return a buffer that is null padded.


The method 'c_str()' will return a pointer to a null-terminated
representation of the 'std::string's content. That is, you will
have an extra null-character tagged on to the 'std::string's
content. If the 'std::string's content contains null-characters,
you cannot process the result of 'c_str()' with the 'str...()'
functions because these might stop at the first embedded
null-character. Thus, you probably should use the 'data()' method
instead because this has the same effect as 'c_str()' except that
it does not add an extra null-character.


Let's say I have a string class that doesn't hold its data in a
contiguous array but still wants to conform to the standard. This would
mean I have to create an array and fill it whenever c_str is called (and
I'm free to delete it whenever a non-const member-function is called.)

Would my class be standard conforming if I only made a c_str array up to
the first null? (I expect that data would have to have all the
characters.)

In other words given:

int main()
{
std::string s = "Hello! World";
s[6] = 0;
const char* foo = s.c_str();
char bar[6];
std::strcpy( bar, foo + 7 );
std::cout << bar;
}

Does the standard define the output of the above program?


The standard specifies:

21.3.6/1 const charT* c_str() const;
Returns: A pointer to the initial element of an array of length size() + 1
whose first size() elements equal the corresponding elements of the string
controlled by *this and whose last element is a null character specified by
charT().
Thus, you are not allowed to stop at the first 0 char. The size and contents
of the array pointed to by the return value of c_str() are completely
specified.
Best

Kai-Uwe Bux

---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Feb 24 '06 #8

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

Similar topics

10
8162
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
3638
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
13235
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
6136
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
9178
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
11493
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
1
5230
by: Jerry | last post by:
I'm new to c++, trying a simple test to read data form a txt file. I compiled with gcc version 3.4.4 20050721 (Red Hat 3.4.4-2). It didn't work as expected, getline() return with null string and failed to read the left data. Is there anything missing? Thanks #include <iostream>
13
6095
by: Pep | last post by:
I have to interface to an older library that uses strings and there is no alternative. I need to pass a string that is padded with null bytes. So how can I append these null bytes to the std::string? Yes I know it would be better to use something like a vector but I do not have that option. Yes I know that I will not be able to use std::string.c_str() but will instead have to use std:;string.getData().
11
2891
by: Jacek Dziedzic | last post by:
Hi! I need a routine like: std::string nth_word(const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" // 'words' are any sequences of non-whitespace characters // leading, trailing and multiple whitespace characters // should be ignored.
0
8176
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
8120
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
8571
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7047
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
6085
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
5537
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
4048
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...
1
1705
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1420
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.