Welcome! Log In Create A New Profile

Advanced

Converting string to char*

Posted by blacksheep 
Announcements Last Post
Announcement SoC Curricula 09/30/2017 01:08PM
Announcement Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
Announcement School of Computing Short Learning Programmes 11/24/2014 08:37AM
Announcement Unisa contact information 07/28/2011 01:28PM
Converting string to char*
March 14, 2006 01:32PM
How do you extract a character pointer (that is char*) from a string? The member functions of the string template I tried was c_str() and data().

All the member functions of string template returns a constant character pointer (that is a const char*).

OR, is there a way to convert a char* to a const char*.
Re: Converting string to char*
March 15, 2006 03:24PM
Im not 100% certain what you mean. Please could you try be a little more specific

Thanks

computergeek
Re: Converting string to char*
March 15, 2006 03:42PM
Oh, my apologies. I thought it was crystal clear.

Which part don't you understand?

Let me try to explain with code.

Consider ProgramOne.cpp

#include <string>
using namespace std;

void main(int argc, char* argv[])
{
string strCppStr = "This is my string";
char* pCStr = strCppStr.c_str();
}

If you compile the above, you get an error stating that it can't convert const char* to char*. this is due to c_str() that returns a const char*.

If you change ProgramOne.cpp to

#include <string>
using namespace std;

void main(int argc, char* argv[])
{
string strCppStr = "This is my string";
const char* pCStr = strCppStr.c_str();
}

It will compile. BUT, I need a char* not a const char* because I want to pass the string as a paraneter to a function that accepts the parameter as a char*.

Hope you understand it now.
Re: Converting string to char*
March 23, 2006 03:39PM
Hi Blacksheep,

I'm not sure how C++ implements it's string library, but I'm guessing that why it returns a const is that somewhere inside a string object you have a "char *" and that c_str() returns a pointer to this. If this is the case, it would make sense why they wouldn't want you to be able to change the string it points to (it would violate the rules of encapsulation more than it already does)

What you can probably do is create a new char *, get the source strings length - strlen(int) - initialse the destination string to the correct size and then use strcpy to copy your "const char*"'s contents into your new "char*".

I don't know if this is the quickest way of doing this, but I'm pretty sure that if my first assumption is correct (about why it's a const) you will need to make a copy of your string before you can use it.

Hope that helps
B.
Re: Converting string to char*
March 23, 2006 03:46PM
Hi Blacksheep, I tried it and it works.

Here is your example updated.

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

int main(int argc, char* argv[])
{
string strCppStr = "This is my string";
const char* pCStr = strCppStr.c_str();
char *newstr = new char[strlen(pCStr)];
strcpy(newstr,pCStr);
cout << newstr << endl;
}

laters
B.
Re: Converting string to char*
March 23, 2006 04:23PM
Yes, that works.
Thank you.

Is it recommended to init newstr first?
That is

memset(newstr,'\0',strlen(pCStr));

before assigning any values to it or is this step completely not required?
Re: Converting string to char*
March 23, 2006 05:37PM
I'm not sure, it may be a good idea - but I think that the const char* returned by c_str() is probably null terminated, so I don't think its too crucial.

hope that helps

B.
Re: Converting string to char*
March 25, 2006 09:14AM
Where did you guys see this: ?

int main(int argc, char* argv[])

this is confusing me,,,,I have never come across this before
Re: Converting string to char*
March 27, 2006 09:16AM
Hi ComputerGeek.

That particular way of making a "main" just allows the user to pass "command line arguments" to your program

so when you run the program from the dos prompt (or linux prompt) your user can invoke it like this

c:\myprogramname argument1 argument2

those two arguments would be available to your program (and they would be in argv, with argc telling you how many arguments the user gave to your program).

Sorry if this isn't a great explanation :-( but it'll make way more sense once you've covered functions and arguments.

I wouldn't worry too much about it just yet though - the program above doesn't use any command line arguments smile

Best
B.
Re: Converting string to char*
March 27, 2006 09:22AM
Its one of the fundamentals of C, or in this case, C++.
Re: Converting string to char*
March 27, 2006 01:30PM
oh okay...because I was beginning to worry there.

So have you all completed the assignment 1 yet. Im busy with question 9 at the moment. I just have question 10 and 7b left. Im a little stuck on 7b.....though.
Re: Converting string to char*
March 27, 2006 01:36PM
I have not really started (busy with taxes). Just browsed through the text book and did an exercise here and there. I am doing certificate course. Our assignments are the text book exercises.
avatar Re: Converting string to char*
May 19, 2006 10:44PM
liliumZA's way is probably the best way of getting a copy of the string data. There is another way though.

string stlStr = "Hello World";

char *chStr = const_cast<char *> (stlStr.c_str());

cout << chStr << endl;

BEWARE!!!!!!!

never use const_cast<> () lightly, You can really mess up your code if you use it carelessly.


Another thing, liliumZA, whenever you dynamically allocate memory using new, you should ALWAYS deallocate is with delete. In this case, since you allocated an array, you should have put the following in your code before the programme exits:

delete [] newstr;
------------------------------
Blacksheep

I am bothered by the reason you want write-access to the internal data of the string class. There is a very good reason that is only supplies constant references. (NOTE, I said references not copies.) If you alter the string, you run the risk of corrupting the original string object.

You mentioned that you want to use the data in a string to pass to another function. I suspect that you're using a function created by another person and you prefer using strings but the other person uses char* instead. I you are going to use this function regularly, have you thought of overloading it?

e.g. Assume the function you want to use takes the c-string as the first parametre and some integers as other parametres. You can create an overloaded function to wrap the other person's function.

errorCode GetOperatingSystem(string &str, int a, int b)
    {
    char *chTemp = new char [str.size()]; //allocate memory for copy
    strcpy(chTemp, str.c_str());
    
    errorCode ec = GetOperatingSystem(chTemp, a, b); // call the original function
    str = chTemp; // copy the results back.
    delete [] chTemp; // deallocate memory

    return ec;
    }

------------------------------
As far as having to initialise the char* first, ordinarily the answer would be "yes". This is just a programming convension, it's not a requirement for c++ compilation. However, the convension has an exception.

If you are certain that you will give the variable a value shortly after creating it AND before you are going to access it, then you don't need to initialise it first. This is what liliumZA did. Another common type of example is if you need to pass a newly created variable to a function in order to give it a value. e.g.

DataRow row;

database.getNextRecord(row);

cout << row.fields[0] << endl;
Re: Converting string to char*
May 22, 2006 10:47AM
Hi robanaurochs

Yeah, I failed to delete. Thanks for pointing that out smile

Although the memory allocated by the new will generally be released when the app terminates anyway, memory leaks are only really problems in "real" programs (and I guess it also depends on the OS). But, yes, it was bad of me.
All I can say is that it's always a bit of a bugger moving back to C++ after spending a year or two working with languages with garbage collection! lol.
avatar Re: Converting string to char*
May 22, 2006 11:38AM
You're right, a lot of compilers add heap management code to your executable but you should never rely on that. Suppose you give your code to somebody who's compiler is more primative. You'll crash their machine.

Call me a purist and a control freak if you like but I hate languages with garbage collection for that very reason - it makes you lazy. [and that you don't have control over WHEN your memory is deallocated]
Re: Converting string to char*
May 22, 2006 11:41AM
Oh yeah, me doing Java at work as well. Luckily I have it embedded in my head to work with classes in C++, declare variables as member variables including pointers, which I then delete in the destructor. My own little humble way of doing garbage collection.

robanaurochs, you mentioned something very interesting which I would like to explore further for my own education. You said and I quote "If you alter the string, you run the risk of corrupting the original string object". Can you elaborate how this string can be corrupted by the pointer?

Maybe someone can help me with this concept as well. is the string class or a template? I always thought of it as a template and not a normal class. I would imagine that the string template is a wrapper for a normal character array in some sort of incapsulating way. Further that its member functions manipulates this character array when you call member functions like append, assign,erase, etc. This indicates to me that if one can extract this character array, it should be safe for usage.

I dont actually understand your GetOperatingSystem function, but maybe I will after a while when I try to run it later. It looks like a recursive function which does not get beyond calling itself. I dont really see how it takes a string and returns a char*. But that is most likely short sightedness on my part.
Re: Converting string to char*
May 22, 2006 11:49AM
LOL - I guess so, but the same can be said about any "high level" features, like "for" loops for example :-P Why not use jmp commands, or better yet, straight machine code. (just kidding of course).

Well, in most languages that have built in garbage collection you can force the garbage collector to run if you have to.

I agree that garbage collection may make you lazy, but the real advantage (and this is why they built garbage collection systems) is that in certain cases keeping track of memory allocation and deallocation just gets out of hand, in a lot of cases it's an added layer of complexity that just doesn't make sense.

But I guess it all has to do with the context you are working in, no one would write an app for custom hardware (like a handheld machine with like 640k ram) using something like .Net. In that case you would want full control over your memory (and in that case I'd probably use plain C over C++ as well, smaller footprint - even though malloc is horrible smile.
But for the most part, when you are writing large business apps that are going to be running of machines with 5 gigs of RAM, I'd much rather just make it easier to concentrate of process rather than memory details.
I guess it just depends on what you are writing?
Re: Converting string to char*
May 22, 2006 12:07PM
robanaurochs, interesting statement you make: "Call me a purist and a control freak if you like but I hate languages with garbage collection for that very reason - it makes you lazy. [and that you don't have control over WHEN your memory is deallocated]"

Are you by any chance reading any of Bjarne Stroustrup's books? Or perhaps you are already majoring in the Computer Science of programming Languages where you intricately study the type strength(strong vs weak, static vs dynamic) of languages, abstraction metholodolgies, matching control flow with optimal data structures, etc.

In which case, maybe you can explain the advantages of having the cleanup control to the developer vs the cleanup conrtoll being part of the compiler/interpreter?

lilumZA, why would you want to use C over C++ ? Is C++ not 99.9999% backwards compatible with C?
avatar Re: Converting string to char*
May 22, 2006 12:15PM
liliumZA

I would never use c over c++. Modern compilers (after the standardisation) produce code that's the same size and speed (if not more so) than c programmes. I'd rather have stricter type checking.

--------------------
Blacksheep

string is part of the STL and is a specialisation of the streambuf<> template class. Don't get it into your head that a template class is not an ordinary class. The only difference is that templates are partial classes/function definitions that are completed by the compiiler when you compile the file. They should be seen as the same otherwise.

I said that you endanger your string class because the character array is not the only data member in the string class. there are others as well. If you modify the character array, you will not be updating those other members and the whole class loses it's integrity. e.g. imagine you reduce the size of the array by shortening the array. The size would not be changed (I'm just guessing here, I don't know what members actually exist). Imagine the case when you use the string's substr() function. It will think that the string is actually longer than is really is - problem.

My GetOperatingSytem() function is hypothetical and it assumes that you're using a function written by someone else:

errorCode GetOperatingSystem(char *, int a, int b);

The function that I wrote above is an overload of this one so that you can pass a string instead of having to convert to a char* all the time. Notice that the only difference is the type of the first parametre. The compiler can see this difference and will call the correct function depending on whether you pass a string or a char*.
Re: Converting string to char*
May 22, 2006 12:40PM
robanaurochs, aaaaaaaaaah! Now I get it. Thanks! I didnt spot the difference in first parameter to start with. Incdidently, the function I was doing the string conversion to char*, was a recursive one. It looks at a root directory, drills down the tree by calling itself and writes all the files it finds in the whole directory tree structure to a single destination directory. BUT it uses the date created field to build the file names of the files being moved to the destination directory with file name nomenclature YYYYMMDD-hhmmss-SSS. I used the _findfirst function to get file attribute values including date created and checking if a file was a folder.

I tried this in Java first, but could only get the last date modified of the files with the Java language. With C++, I could actually get the creation date of the file. There were also instances where I wwanted to use things like default parameters and multiple inheritance, but would not do it in Java. I could do it in C++.

Why am I sharing this little details? Well, one would think that with advance features like garbage collection, such simple features as the ones mentioned in previous paragraph would exist in a very modern lang like Java. Unless off course I didnt do my homework correctly. I still like Java though. When I asked the Q in a Java forum of getting the creation date of the file, it was suggested I switch to the Java Native Interface. For things like Multiple inheritance, abstract classes implemented as interfaces were suggested as an alternative.

I find that very interesting.
Sorry, only registered users may post in this forum.

Click here to login