[Dev] null terms for strings

M. Mueller dev@trilug.org
Tue, 7 May 2002 14:30:32 -0400


Here's a little program that captures a problem I had today.  I have a map 
container, map<string, t_myStruc), that I want to duplicate on another 
machine.  I pack each entry into datagram and send it via sockets to another 
machine where each packet is collected and used to build a copy of the map 
entry by entry.  So, I convert the string key to an array of chars for the 
journey to the other side.  In the process I got confused about the function 
of null terminators on char array strings versus string objects.

To compile: g++ -o test test.cpp

<snip start>
#include <string>
using namespace std;

main()
{
	string a;
	a  = 'a';
	a += ' ';
	a += 's';
	a += 't';
	a += 'r';
	a += 'i';
	a += 'n';
	a += 'g';
	a += '\0';
	string b;
	b  = 'a';
	b += ' ';
	b += 's';
	b += 't';
	b += 'r';
	b += 'i';
	b += 'n';
	b += 'g';

	if (a == b) 
		cout << "a equals b\n";
	else
		cout << "a not equals b\n";

	if (strcmp(a.c_str(), b.c_str()) == 0)
		cout << "a.c_str() equals b.c_str()\n";
	else 
		cout << "a.c_str() not equals b.c_str()\n";
	
}
<snip end>


-- 
Michael Mueller
Signalnetware, Inc.
www.signalnetware.com
919.621.6090