1

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?

3
  • Try dereferencing ptr in the while loop check. Commented Apr 16, 2013 at 11:53
  • Also, you are leaking memory with that new (which isn't needed anyway). Commented Apr 16, 2013 at 11:58
  • I cleaned up your code.. next time try not to use tabs and format it correctly before you post to SO. Commented Apr 16, 2013 at 12:03

4 Answers 4

4
while( ptr != '\0')

should be

while (*ptr != '\0')
Sign up to request clarification or add additional context in comments.

Comments

4

I think you are missing an asterisk here :

while( ptr != '\0')

to make it

while( *ptr != '\0')

You can also access each individual element of a string like this:

string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;

You can also iterate over a string:

string str ("Hello World");
string::iterator it;
for (int index = 0, it = str.begin() ; it < str.end(); ++it)
   cout << index++ << *it;

or

string str ("Hello World");
string::iterator it;
for (int index = 0, it = str.begin() ; it < str.end(); ++it, ++index)
   cout << index << *it;

or

string str ("Hello World");
string::iterator it;
int index = 0;
for (it = str.begin() ; it < str.end(); ++it, ++index)
   cout << index << *it;

Understanding that you are looking for the null-terminating character in a C-style string, but if you have your druthers, stay with std::string.

3 Comments

0A0D Thanks for the detailed example.. I know all these .. Was just exploring c_str() function..cheers
How would it be of type int in your 2nd and 3rd example? I don't think that will compile.
@0x499602D2: It's not of type int.
4

Should be

    while( *ptr != '\0')
        {
            cout << "*ptr : "<< *ptr << endl;
            ptr++;
    }

and

    const char * st = new char [str1.length()+1];
    st=str1.c_str();//Converts to null terminated String

should be

    char * st = new char [str1.length()+1];
    strcpy(st, str1.c_str());//Copies the characters

or it could be

    const char * st = str1.c_str();//Converts to null terminated String

Your version is a bad mix of the two because it allocates memory as if it was going to copy the characters, but then doesn't copy anything.

You do realise you can access the individual characters of a std::string too? Just str1[0], str1[1], str1[i] etc.

7 Comments

Yes.. Using iterator .. Just exploring c_str() function
OK, but not only an iterator, also using [].
while( ptr != '\0')--Oops silly mistake ...strcpy(st, str1.c_str());//Copies the characters throws error: Test.cpp:19: error: invalid conversion from const char*' to char' Test.cpp:19: error: initializing argument 1 of `char* strcpy(char*, const char*)' -- st=str1.c_str(); works fine
@GauravK OK should be char * st = new char [str1.length()+1]; I've updated my answer.
@GauravK There's nothing wrong with it, it depends what you want. Do you want a pointer to a copy of the original characters, or do you want a pointer to the original characters themselves? If you want to point to the original characters then there is no need to allocate any memory, the allocation is needed only if you need somewhere to copy the characters to.
|
0

This works fine.. Thanks for the responses.

 int main()
    {
        string str1("Alpha");
            cout << str1 << endl;




        const char * st = new char [str1.length()+1];
            st=str1.c_str();
           //strcpy(st, str1.c_str());//Copies the characters
           //throws error:
           //Test.cpp:19: error: invalid conversion from `const char*' to `char*'
           //Test.cpp:19: error:   initializing argument 1 of `char* strcpy(char*, const char*)'

            const char* ptr=st;


            while( *ptr != '\0')
                {
                    cout << "*ptr : "<< *ptr << endl;
                    ptr++;
            }
        return 0;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.