CString Vs std::string
-
With CString, we can perform an operation something like:
CString strMarks;
strMarks.Format("I got %d marks",marks);Can we perform similar operation using std::string ??? If yes, then how ???
Try this:
char buffer\[200\] = {0}; std::string str = ""; int i = 9; sprintf(buffer, "\\n\\nThis is number: %d\\n\\n", i); str = buffer; printf(str.c\_str());
- Nitron
"Those that say a task is impossible shouldn't interrupt the ones who are doing it." - Chinese Proverb
-
With CString, we can perform an operation something like:
CString strMarks;
strMarks.Format("I got %d marks",marks);Can we perform similar operation using std::string ??? If yes, then how ???
Unfortunately, you can't. In concept of C++ std library you must use streams (like as stdout, stdin and etc). This method was perfectly described by Alexandrescu in his book "Modern C++...". But personally I like to use old good method as Format. And I have invented my own function. May be it will be useful for you
string_smart Format(cstr szText,...)
{
cstr szPtr=szText;
size_t lLen;
//Calculating Average length
for (lLen=0;*szPtr; ++szPtr,(*szPtr=='%') ?lLen+=10:lLen++);string\_cstr strRes(++lLen); va\_list marker; va\_start( marker, szText); while (\_vsnprintf(strRes.buffer(),strRes.buffer\_size()-1,szText,marker) <0 ) strRes.reserve(strRes.buffer\_size()\*2); //\_ASSERTE( \_CrtCheckMemory( )); strRes.buffer()\[strRes.buffer\_size()-1\]='\\0'; //Don't remove this line! strRes.recalc\_len(); va\_end( marker ); return strRes;
}
This function works with my class string_smart, but it is not hard to remake it for std::string
-
With CString, we can perform an operation something like:
CString strMarks;
strMarks.Format("I got %d marks",marks);Can we perform similar operation using std::string ??? If yes, then how ???
Yes you can, using the
stringstream
class:#include <string>
#include <sstream>ostringstream strm;
string strMarks;strm << "I got " << marks << " marks" << ends;
strMarks = strm.str();--Mike-- Friday's GoogleFight results: Britney Spears 2,190,000 - Erica Weichers 23 :( 1ClickPicGrabber - Grab & organize pictures from your favorite web pages, with 1 click! My really out-of-date homepage Sonork-100.19012 Acid_Helm
-
Yes you can, using the
stringstream
class:#include <string>
#include <sstream>ostringstream strm;
string strMarks;strm << "I got " << marks << " marks" << ends;
strMarks = strm.str();--Mike-- Friday's GoogleFight results: Britney Spears 2,190,000 - Erica Weichers 23 :( 1ClickPicGrabber - Grab & organize pictures from your favorite web pages, with 1 click! My really out-of-date homepage Sonork-100.19012 Acid_Helm
I would just rearange it a little:
#include <string>
#include <sstream>
std::ostringstream strm;
strm << "I got " << marks << " marks" << std::ends;
std::string strMarks = strm.str();:beer: