Thread: Converting an std::string to a const char *

  1. #1
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968

    Converting an std::string to a const char *

    I've googled, but I can't find anything really comprehensive, so I decided I'd ask you guys..

    How in the world do you convert an std::string to a const char* ?/


    It seems like the ifstream doesn't like working with std::string's, only const char *'s..

    Helllp
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Use the string's c_str() member function.

    [edit]There shouldn't be any problem using string containers with ifstream. Perhaps you should show a minimal code sample that is causing you problems.[/edit]
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    The getline version that works with strings is a free function
    Code:
    std::string str;
    std::getline(std::cin,str);
    Note also the the pointer returned by c_str() is only good so long as the std::string exists, and is unmodified. Thus it's fine for passing to functions, but don't try returning a c_str() from a local string and so forth.

  4. #4
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Here is the broken bit of code


    Code:
    bool MS3DModel::Load_MS3D_Model(std::string Filename)
    {
    	ifstream inputFile( Filename, ios::in | ios::binary | ios::nocreate );
    	if ( inputFile.fail())
    		return false;	// "Couldn't open the model file."
    This spawns this error

    Code:
    \\student\courses\cedar_cliff\computer\senior project\auditorium\resource_manager\ms3d.cpp(142) : error C2664: '__thiscall ifstream::ifstream(const char *,int,int)' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_tra
    its<char>,class std::allocator<char> >' to 'const char *'
    ifstream input file only takes a const char * for its first parameter

    EDIT:

    Fixed it with c_str()

    Code:
    bool MS3DModel::Load_MS3D_Model(std::string Filename)
    {
    	const char* cstr = Filename.c_str();
    
    	ifstream inputFile( cstr, ios::in | ios::binary | ios::nocreate );
    	if ( inputFile.fail())
    		return false;	// "Couldn't open the model file."
    Last edited by Shamino; 01-24-2006 at 10:34 AM.
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    bool MS3DModel::Load_MS3D_Model(std::string Filename)
    Consider passing strings by reference.
    Code:
    bool MS3DModel::Load_MS3D_Model(std::string &Filename)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    In this case const reference would be preferred.

  7. #7
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    so instead of passing it as a value pass it as a reference? and then still perform the conversion?

    Can you explain why?
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  8. #8
    I am me, who else?
    Join Date
    Oct 2002
    Posts
    250
    Technically you can save a further step and directly pass it as:

    Code:
    bool MS3DModel::Load_MS3D_Model( filename.c_str() );
    which passes as a const char *.

  9. #9
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by dpro
    Technically you can save a further step and directly pass it as:

    Code:
    bool MS3DModel::Load_MS3D_Model( filename.c_str() );
    which passes as a const char *.
    that doesn't really gain you anything. on most platforms a pointer and a reference produce equivalent code. so all you've really done is to deprive yourself of any std::string functionality (append, finding, etc) within Load_MS3D_Model
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  10. #10
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Fortunately the only thing I *might* want Load_MS3D_Models to do is assert that the file extension is correct.. That I can do with a char array though can't I?
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  11. #11
    I am me, who else?
    Join Date
    Oct 2002
    Posts
    250
    Actually I recind my earlier statement, in thinking it through it is better to pass it by const reference than to convert and send the parameter. You gain much greater functionality through the code to leave it as a const ref. So listen to other people and forget I said anything about converting it as a const char *
    Last edited by dpro; 01-24-2006 at 03:32 PM. Reason: Cannot spell :(

  12. #12
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    Quote Originally Posted by dpro
    While that is true, I suppose it depends on how you look at it. I suppose if you want to change the parameter, it would be fine, but to me it seems simpler that way, but you are free to feel differently of course.
    even if you don't want to change the parameter, std::string is still useful. what if you want to check that filename ends in ".md3" or similar? you'd have to use one of the c string functions (can't even remember which one). why mix APIs when you don't have to?

    Basically, stay as high-level as you can for as long as you can.
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  13. #13
    I am me, who else?
    Join Date
    Oct 2002
    Posts
    250
    Lol don't worry about it chaos, I know I was just being narrow-sighted, I edited my post to reflect this. I'm a cranky man who is tired and forgot his c++ programming pills today.

  14. #14
    Absent Minded Programmer
    Join Date
    May 2005
    Posts
    968
    Well, you can't exactly see the top level of my implementation..

    At the top, while we're still working with an std::string, I do a file extension check to decide which loader function we will use..

    then according to what the file extension is == to we pick the proper loader function and let it fly from there...
    Sometimes I forget what I am doing when I enter a room, actually, quite often.

  15. #15
    I am me, who else?
    Join Date
    Oct 2002
    Posts
    250
    Still its better to stay and keep your options open as a std::string, rather than limit them by transferring over to a c-style string. More flexible that way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcat - cannot convert char to const char
    By ulillillia in forum C Programming
    Replies: 14
    Last Post: 12-07-2006, 10:00 AM
  2. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  3. fatal error LNK1104
    By DMH in forum C++ Programming
    Replies: 2
    Last Post: 11-16-2005, 03:46 AM
  4. Display Lists (OpenGL)
    By Shamino in forum Game Programming
    Replies: 11
    Last Post: 06-05-2005, 12:11 PM
  5. Debugging help
    By cuddlez.ini in forum C++ Programming
    Replies: 3
    Last Post: 10-24-2004, 07:08 PM