Converting a const char * to std::string - c++ - Stack Overflow

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

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 #include constchar*f(){return"HelloFletch";} intmain() { std::strings1=f(); std::strings2; s2=f(); std::strings3; s3.assign(f()); std::cout<c`beshortenedinJavascript? Howwouldyoustandardizeon-callexpectationsacrosssoftwareteamswhenthey'vedivergedatthesamesalarylevel? IssoundofUSSEnterprise’sautomaticdooropeningindeedtoiletflushingsound? Howtallarethemushrooms? Whycan'tItakephotosinsideofstoresinPortugal? WhatarethecorrectspecsforanSNESpowersupply? WhatisthestrongestmetalintheDCuniverse? ShortofattackingaNATOcountry,isthereanyotherthingRussiacandototriggerdirectAmericanmilitaryconfrontation? Wouldasolarsystemwithfourearthsdirectlyoppositetoeachotherhavedifferentflora? WhyareRoevWadeandPlannedParenthoodvCaseyabbreviatedasRoeandCasey? IterativeSmallestComplement DoesthereexistaLatinsquareoforder9forwhichits9brokendiagonalsand9brokenantidiagonalsaretransversals? /var/loghasreached56.6GB.Howtocleanitandmakemorespace? Howlongcanmycharactersurvivewithoutsleep? HowdoIsetvaluenodeto#frameusingpython WhydoIgetaccostedfortakingphotosofawarmemorial? Doescookingfoodinsidealockedpressurecookerpreserveitsimilartocanning? Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? BivariateHermitePolynomials 28yofriendlookingtoattenedundergraddegreewithouttransferringanycredits Findingthelinenumberoffirstoccurrenceofatextinbashscript JPLHorizons-"highlyaccuratemeasurementsofplanetarypositions"-howdotheydoit? Formallanguagerewriterules:strangenotation Palindromeanimationpausingatbeginningandend morehotquestions lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?