Weird String Problem

Started by
6 comments, last by xorjesus 19 years, 10 months ago
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

}
I study day and night, memorizing the game.
Advertisement
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.
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 :]
I study day and night, memorizing the game.
Why don''t you just make your function return an std::string?
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]
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.
I study day and night, memorizing the game.
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:
// Prototypestring GetString(int a, char b, float c, Object* d);...// Call the functioncout << GetString( GetInteger(), GetChar(), GetFloat(), GetObjectPointer() ).c_str() << endl;

Although readability can hinder your like of such calls!
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;};

This topic is closed to new replies.

Advertisement