Convert std::string to const char* in C++ - Techie Delight

文章推薦指數: 80 %
投票人數:10人

We can easily get a const char* from the std::string in constant time with the help of the string::c_str function. The returned pointer is backed by the ... Skiptocontent Thispostwilldiscusshowtoconvertastd::stringtoconstchar*inC++.Thereturnedpointershouldpointtoachararraycontainingthesamesequenceofcharactersaspresentinthestringobjectandanadditionalnullterminator(‘\0’character)attheend. 1.Usingstring::c_strfunction Wecaneasilygetaconstchar*fromthestd::stringinconstanttimewiththehelpofthestring::c_strfunction.Thereturnedpointerisbackedbytheinternalarrayusedbythestringobject,andifthestringobjectismodified,thereturnedpointerwillalsobeinvalidated. 123456789101112 #include#include intmain(){    std::stringstr="std::stringtoconstchar*";    constchar*c=str.c_str();     std::cout<#include intmain(){    std::stringstr="std::stringtoconstchar*";     charconst*c=str.data();    std::cout<#include intmain(){    std::stringstr="std::stringtoconstchar*";     constchar*c=&str[0];    std::cout<



請為這篇文章評分?