About stringsteam
stringsteam is a standard C++ stl library that helps to processing string as steam. There are three types of stringsteam:
istringsteam : processing input string ostringsteam: processing output string stringsteam: processing both input/output steam
It’s high recommend to use stringsteam instead of sprintf because stringsteam is more safer than sprintf. Look at this code:
int n = 12345; char szbuf[4] = {0}; sprintf(szbuf, "%d", n)
There are two potential problems in this piece of code: the format must match the covert type. Say if “%d” is “%f” or n is a float number, it crashes. If szbuf is shorter than the converted result, it crashes because sprintf doesn’t check the buffer length before it copies, so the buffer overflows. (sprintf_s would be more safer where it requires a buffer size as an argument in function if you really want to use sprintf to format a string).
There is no such crash when using stringsteam. compiler knows what type it is of n so it will automatically convert n as %d when it is a integer or %f when it is a float. The stream is dynamic so you don’t need to worry about memory overflow when it copies string.
how to use stringsteam
string res = "10000"; int n = 0; steam<<res; //steam now is 10000; steam>>n; //n is 1000 now
Following is a code example to use stringsteam for tree serialization and deserialization. Let’s say we have a binary tree like the following graph:
1 / \ serialization string: [1,2,3] 2 3 1 \ 2 serialization string: [1,null,2,3] / 3
For tree [1,2,3] serialization, uses ostringsteam:
the output string return:”1 2 # # 3 # #”
Then use “1 2 # # 3 # #” as input argument to deserialize a tree: