What is use of c_str function In c++

前端 未结 7 1245
忘了有多久
忘了有多久 2020-12-04 06:30

I have just started reading C++ and found c++ having rich functions for string manipulation which C does not have. I am reading these function and came across c_str()<

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 06:48

    In C++, you define your strings as

    std::string MyString;

    instead of

    char MyString[20];.

    While writing C++ code, you encounter some C functions which require C string as parameter.
    Like below:

    void IAmACFunction(int abc, float bcd, const char * cstring);

    Now there is a problem. You are working with C++ and you are using std::string string variables. But this C function is asking for a C string. How do you convert your std::string to a standard C string?

    Like this:

    std::string MyString;
    // ...
    MyString = "Hello world!";
    // ...
    IAmACFunction(5, 2.45f, MyString.c_str());
    

    This is what c_str() is for.

    Note that, for std::wstring strings, c_str() returns a const w_char *.

提交回复
热议问题