Archived

This topic is now archived and is closed to further replies.

xorjesus

Weird String Problem

Recommended Posts

For some reason when I have a string object return a c-string, it returns absolute garbage. Though if copy or print the cstring without returning it, everything works fine. How can I make it so it returns a non garbage c-string portion.
const char * PrintHelloWorld()
{
	string s = "Hello World";
	cout << s.c_str() << endl; // prints Hello World

	return s.c_str();
}

void main()
{
	cout << PrintHelloWorld() << endl; // Prints garbage

}

Share this post


Link to post
Share on other sites
When the string object goes out of scope, so does its internal buffer. And you get garbage

You''ll have to dynamically create a new character buffer, copy the string into that, and return a pointer to the buffer. Then it needs to be free''d. A bit of a hassle, but that''s how you get around the lifetime issues.

Share this post


Link to post
Share on other sites
Ahh that makes sense! Thank you zipster. Guess I''ll just use an auto_ptr. I was using a string in place of a normal c-string for the purpose of destroying the buffer after the string goes out of scope. I guess it worked too well :]

Share this post


Link to post
Share on other sites
quote:
Original post by Deyja
Why don't you just make your function return an std::string?


ala:

std::string PrintHelloWorld()
{
string s = "Hello World";
cout << s.c_str() << endl; // prints Hello World

return s;
}

void main()
{
cout << PrintHelloWorld().c_str() << endl; // prints Hello World

}


[edited by - Palidine on May 26, 2004 9:19:31 PM]

Share this post


Link to post
Share on other sites
Wow, I didn''t realize I could do that Deyja. Thank you for using your pychic powers Palidine, and knowing I would ask how to do that. Thats crazy, whats that called? I didn''t know you could use functions like that.

Share this post


Link to post
Share on other sites
Different types of expressions evaluate to different types, and it just so happens that functional expressions evaluate to their return type This allows you to make all sorts of crazy calls:

// Prototype

string GetString(int a, char b, float c, Object* d);
.
.
.
// Call the function

cout << GetString( GetInteger(), GetChar(), GetFloat(), GetObjectPointer() ).c_str() << endl;

Although readability can hinder your like of such calls!

Share this post


Link to post
Share on other sites
just include
instead of and use the std::cout, so you sont need that c_str()-crap... it fucking hurts me!


#include<string>
#include<iostream>

int main(int argc, char** argv)
{
std::string bla("bla");
std::cout<<bla<<std::endl;
std::cin>>bla;
return 0;
};

Share this post


Link to post
Share on other sites