I am not able to figure out the code required for accepting a string from user , but the memory for it should be dynamically allocated and referenced using pointer.

Have a look at the following:
char *p=new char[length_of_string+1];

This statement would work to dynamically allocate the string ,but still I require the length and that depends on user's input.

Is there a better way to handle this situation? Please help!!!

Recommended Answers

All 7 Replies

Your best option is to use the std::string class. It handles memory for you behind the scenes and is dynamic without requiring lengths beforehand:

#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cout<<"Enter a string: ";

    if ( getline ( std::cin, s ) )
        std::cout<<"You entered \""<< s <<"\"\n";
}

If you must use pointers and dynamic allocation, you'll end up having to build your string in regular sized blocks. That way you can support a dynamic size, but you still have the necessary length for reading a block. I don't recommend this approach unless you have no other options.

int i=0; //Temp var
char *p=new char; // p having zero length
while((*p=getche())!='\r') // getting character
i++; // increment according to need


I think this will help you!

>I think this will help you!
Not really. What you posted is hopelessly broken.

>char *p=new char; // p having zero length
A dynamic array of zero length isn't the same as a dynamic array of infinite length. In fact, trying to allocate 0 bytes of memory has implementation-defined behavior on top of being utterly useless.

>while((*p=getche())!='\r') // getting character
Regardless of the implementation-defined behavior of allocating 0 bytes, trying to write to the memory is always undefined behavior. You also never change p, so getche is always overwriting the same character.

I know u are right but that some thing according to his needs , he can use "getchar" instead of "getche".

>he can use "getchar" instead of "getche".
I think you missed the point that the way you're allocating and accessing memory is wrong in every possible way.

Well actually i mean "while((*p=getchar())!='\n') i++; ".Thank You pointing out my mistake .

>Well actually i mean "while((*p=getchar())!='\n') i++; ".Thank You pointing out my mistake .
It's still wrong. Are you trying to be obtuse? Your code is wrong, and there's no way to fix it if you continue to believe that new char[0] magically gives you a dynamic array of infinite size. It doesn't work that way. You have to allocate at least as many bytes as you store, and no less. Until you do that, it's quite pointless to quibble about how you read characters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.