How to convert string into string into a null-terminated string.



/*
 * session9.cpp
 *
 *  Created on: Aug 11, 2013
 *      Author: kobee
 */

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main(){
	string str("This is a test.");
	char cstr[80];

	const char *p = str.c_str();
	cout << p;

	// Copy the string into a statically allocated array.
	//
	// First, confirm that the array is long enough
	// to hold the string.
	if(sizeof(cstr) < str.size()+1){
		cout << "Array is too small to hold the string.\n";
		return 0;
	}

	strcpy(cstr,p);
	cout << "Here is the string copied into cstr:\n" << cstr << "\n\n";

	// Next,copy the string into a dynamically allocated array.
	try {
		// Dynamically allocate the array
		char *p2 = new char[str.size() + 1];

		// copy the string into the array
		strcpy(p2,str.c_str());
		cout << "String after being copied into dynamically-allocated array:\n";
		cout << p2 << endl;

		delete[] p2;
	} catch (bad_alloc e) {
		cout << "Allocation Failure\n" << e.what();
		return 1;
	}

	return 0;
}

Reference : Herb Schildt’s C++ Programming Cookbook

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: