Converting a const char * to std::string - c++ - Stack Overflow
文章推薦指數: 80 %
I've got a const char * returned from a processing function, and I'd like to convert/assign it to an instance of std::string for further manipulation.
Resultsfromthe2022DeveloperSurveyarenowavailable
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Convertingaconstchar*tostd::string[duplicate]
AskQuestion
Asked
8yearsago
Modified
6years,7monthsago
Viewed
128ktimes
27
4
Thisquestionalreadyhasanswershere:
Howtoconvertaconstchar*tostd::string[duplicate]
(6answers)
Closed8yearsago.
I'vegotaconstchar*returnedfromaprocessingfunction,andI'dliketoconvert/assignittoaninstanceofstd::stringforfurthermanipulation.Thisseemslikeitshouldbestraight-forward,butI'venotbeenabletofindanydocumentationshowinghowitshouldbedone.Obviously,I'mmissingsomething.Insightsappreciated.
c++stringchar
Share
Follow
askedJun9,2014at19:55
JustinFletcherJustinFletcher
2,23922goldbadges1616silverbadges3131bronzebadges
5
7
It'soneoftheconstructoroptions,std::string(constchar*cstr)
– aruisdante
Jun9,2014at19:58
std::strings=f();
– AlanStokes
Jun9,2014at19:59
Thisquestionwascausedbyaproblemthatcannolongerbereproducedorasimpletypographicalerror.Whilesimilarquestionsmaybeon-topichere,thisonewasresolvedinamannerunlikelytohelpfuturereaders.Thiscanoftenbeavoidedbyidentifyingandcloselyinspectingtheshortestprogramnecessarytoreproducetheproblembeforeposting.
– πάνταῥεῖ
Jun9,2014at20:05
Wow,-5.Ididn'tthinkitwasaterriblequestion...Ohwell.
– JustinFletcher
Jun9,2014at21:06
1
+1:Yeah-9forthisquestioniskindofridiculous.Theotherquestionisslightlydifferentbecauseithasalengthrequirementwhichmaynotberelevanttomanypeople.
– User
Aug15,2014at22:39
Addacomment
|
5Answers
5
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
59
std::stringhasaconstructorfromconstchar*.Thismeansthatitislegaltowrite:
constchar*str="hello";
std::strings=str;
Share
Follow
answeredJun9,2014at19:59
IvayloStrandjevIvayloStrandjev
66.7k1515goldbadges119119silverbadges170170bronzebadges
1
6
Justmakesurethatyourchar*isn'tNULL,orelsethebehaviorisundefined.
– TrevorHickey
Nov6,2015at20:18
Addacomment
|
20
Try
constchar*s="hello";
std::stringstr(s);
willdothetrick.
Share
Follow
answeredJun9,2014at19:58
EdHealEdHeal
57.7k1616goldbadges8282silverbadges120120bronzebadges
4
1
Ifinditamusingthatwechosethesameexamplestringandalmostthesame(justswapped)variablenames:-)
– IvayloStrandjev
Jun9,2014at20:02
1
Justmakesurethatyourchar*isn'tNULL,orelsethebehaviorisundefined.
– TrevorHickey
Nov6,2015at20:48
Howisitgoingtobenull?
– EdHeal
Nov6,2015at20:50
3
@EdHealIt'snotinyourexample,butachar*ingeneralcouldbe.I'mleavingadisclaimerforothers.Forexample,I'musingthegetenv()function.Iftheenvironmentvariabledoesn'texistitwillreturnanull.Acheckwouldbeneededbeforeconstructingastringofthatfunction'sreturnvalue.ThisisrelevantsinceOPsaysthey"gotaconstchar*returnedfromaprocessingfunction".
– TrevorHickey
Nov6,2015at21:02
Addacomment
|
4
You'vegotalotofoptions:
constchar*dosth(){return"hey";}
strings1=dosth();
strings2(dosth());
strings3{dosth()};
autos4=(string)dosth();
LiveDemo,Documentation
Notethats3ands4areC++11features,ifyoushouldstillworkwithanoldornon-compliantcompileryouwouldhavetoworkwithoneoftheotheroptions.
Share
Follow
editedJun9,2014at20:16
answeredJun9,2014at20:04
AppleshellAppleshell
6,79855goldbadges4646silverbadges9494bronzebadges
2
Pleaseaddanotethatsomeoftheexamplesrequirec++11
– IvayloStrandjev
Jun9,2014at20:05
1
Justmakesurethatyourchar*isn'tNULL,orelsethebehaviorisundefined.
– TrevorHickey
Nov6,2015at20:48
Addacomment
|
3
Therearethreepossibilities.Youcanuseaconstructor,anassignmentoperatorormemberfunctionassign(ifdonottakeintoaccountmemberfunctioninsertthoughitisalsocanbeused:))`
Forexample
#include
延伸文章資訊
- 1string、const char*、 char* 、char[]相互转换(全) - CSDN博客
string、const char*、 char* 、char[]四者类型经常会需要转化。 一:转化总结形式如下:. 使用时,要对源格式和目标格式进行初始化。
- 2const char to string Code Example - Code Grepper
const char * s = "hello"; std::string str(s);
- 3How to convert an std::string to const char* or char* in C++?
You can use the c_str() method of the string class to get a const char* with the string contents....
- 4指標與字串
const char *text = "hello";. 如此一來,試圖透過 text 改變字元,編譯器會失敗,從而避免了執行時期的錯誤。
- 5C++ Char Array to String - Tutorial Kart