std::string question

I

Ioannis Vranos

Dylan said:
How do I insert a NULL character into a std::string?

thanks



It would be better if you told us exactly what do you want to do.






Regards,

Ioannis Vranos
 
J

John Harrison

Dylan said:
How do I insert a NULL character into a std::string?

thanks

Exactly the same way as any other character, for instance.

std::string s = "abc";

std::cout << s.size(); // prints 3
s.insert(s.begin(), '\0'); // insert nul at beginning
std::cout << s.size(); // prints 4

john
 
T

Thomas Matthews

A

Ali Cehreli

std::string example("Hello");
example += "\0";

Unfortunately that won't work because the string literal "\0" would be
parsed as the empty string "".

This works:

example += '\0';

Ali
 
M

Mike Wahler

Dylan said:
How do I insert a NULL character into a std::string?

The macro 'NULL' does not refer to a character value,
but to a pointer value.

The term 'NUL' is defined by the ASCII (and perhaps
others) character set as the value zero. The C++
language does not require use of a particular character
set (only that it contain a minimum set of values).
The term 'NUL' is not defined by standard C++ (but
the value zero is). The value zero is one of the
required values for character types.


#include <iostream>
#include <string>

int main()
{
std::string s("Hello world");

std::cout << "Before insert:\n\n";

std::cout << "string 's' has a length of "
<< s.size() << " characters.\n";

std::cout << "Output of std::cout << s :\n"
<< s << '\n';

std::cout.put('\n');

s.insert(5, 1, 0); /* insert one character with value zero
before position 5 */

std::cout << "After insert:\n\n";

std::cout << "string 's' has a length of "
<< s.size() << " characters.\n";

std::cout << "Output of std::cout << s :\n"
<< s << '\n';

return 0;
}

-Mike
 
D

David Harmon

On Wed, 23 Jun 2004 18:03:10 GMT in comp.lang.c++, "Mike Wahler"
The macro 'NULL' does not refer to a character value,
but to a pointer value.

Sorry, but that's a dangerous misstatement. In C++, NULL must be
defined as a null pointer constant, which makes it an integral value not
a pointer value. So, given e.g.

int f(int);
int f(void *);
f(NULL);

The first f(int) is always called, and not the second f(void *).
This can be a surprise.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,938
Members
47,474
Latest member
VivianStuk

Latest Threads

Top