I am trying to convert a C++ string object to C-Style NULL terminated string using c_str() and then trying to access individual character as it can be done for c-style string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1("Alpha");
cout << str1 << endl;
const char * st = new char [str1.length()+1];
st = str1.c_str(); // Converts to null terminated string
const char* ptr=st;
// Manually Showing each character
// correctly shows each character
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
ptr++;
cout << "# Null Character :" << *ptr << endl;
// But below loop does not terminate
// It does not find '\0' i.e. null
while( ptr != '\0')
{
cout << "*ptr : "<< *ptr << endl;
ptr++;
}
return 0;
}
But seems like it does not add '\0' at the end and the loop does not terminate. Where I am going wrong ?
C-style string (e.g. char* st="Alpha";) can be accessed with the loop shown in the code but when the conversion from string object to c-style string happens, it can not.How do I do it?
ptrin thewhileloop check.new(which isn't needed anyway).