What I can use instead of strstream::freeze? - c++

I am working on some old c++ codes and it has strstream class which is deprecated. I need to replace them with working ones.
In my header file I got this:
ostrstream tokenBuff;
and .c file that uses header:
tokenBuff.freeze(0);
tokenBuff.seekp(0);
I replaced ostrstream with ostringstream. ostringstream has seekp() but not freeze(). How can I deal with this problem. Thanks.

You don't need freeze() in case of std::ostringstream - the necessity of calling this function was actually one of the reasons why strstream got deprecated in the first place. Because of its design (returning char* from str()) it wasn't clear who should clean the buffer that strstream holds and freeze() had to be used to signal that you want strstream itself to do it after every call to str() - in case of std::ostringstream you don't need to worry about this as str() returns a copy of the std::string.

There is no replacement for freeze in ostringsteam since it is no longer needed. In ostrstream freeze() is used to work around the deficiency that str() returns a c-style (char *) string.

Related

Are the methods in the <cstring> applicable for string class too?

I've tried out using memcpy() method to strings but was getting a "no matching function call" although it works perfectly when I use an array of char[].
Can someone explain why?
www.cplusplus.com/reference/cstring/memcpy/
std::string is an object, not a contiguous array of bytes (which is what memcpy expects). std::string is not char*; std::string contains char* (somewhere really deep).
Although you can pull out the std::string inner byte array by using &str[0] (see note), I strongly encourage you not to. Almost anything you need to do already is implemented as a std::string method. Including appending, subtracting, transforming and anything that makes sense with a text object.
So yes, you can do something as stupid as:
std::string str (100,0);
memcpy(&str[0],"hello world", 11);
but you shouldn't.
Even if you do need memcpy behaviuor, try to use std::copy instead.
Note: this is often done with C functions that expects some buffer, while the developer wants to maintain a RAII style in his code. So he or she produces std::string object but passes it as C string. But if you do clean C++ code you don't need to.
Because there's no matching function call. You're trying to use C library functions with C++ types.

What should I use instead of std::ostrstream?

I like to use std::ostrstream to format text but not print it to stdout but instead write it into an std::string (by accessing the std::ostrstream::str() member). Apparently this is deprecated now. So, how am I supposed to write formatted objects to a string, with the same convenience as when writing to a stream?
You could use std::ostringstream. Similarly, instead of std::istrstream you should use std::istringstream. You need to include the <sstream> header for these classes.
You could also see this question which explains why strstream was deprecated.
As others have already said, std::ostringstream is the replacement.
It's more convenient (and safer) than std::ostrstream because it manages all memory automatically so you don't need to call freeze(false) to ensure the memory gets freed when you're finished with it.
You should use std::stringstream. Also, see boost::lexical_cast.
std::stringstream supports both << and >>. std::ostringstream only supports <<, and std::istringstream only supports >>. Often I find it convenient to be able to use both operators.
You can also use boost::format. Then you can do things like:
int a = 1;
std::string b("foo");
std::string s = boost::str(
boost::format("some text, some vars=%1%, %2%, %1%") % a % b % a);
Then s would contain "some text, some vars=1, foo, 1".
This is, in my opinion, more convenient in some cases than using operator <<.
As a reference, I also include the format specification.

Trouble with logfile output - difference between string and c_str - C++

I am trying to finalize my logging class. I have written it from scratch and do not wish to use an alternative library of any kind. My problem lies within the fact that my logger has trouble outputting std::strings and only works when I denote it with the string.c_str() function.
Here is my logfile output function:
void Log::writeSuccess(char * text,...)
{
// Grab the variables and insert them
va_list ap;
va_start(ap, text);
char buff[BUFFER_SIZE];
vsnprintf(buff, sizeof(buff), text, ap);
// Output to the log
logfile << "<-!-> " << buff << endl;
}
Here is a sample call to my log class object (ignore the uselessness of the call):
string test("This is a test string!");
errorLog.writeSuccess("Output: %s", test);
I end up with random characters and garbled output.
However, when I append the string, test with .c_str(), it outputs the text correctly.
The whole reason I am trying to avoid cstrings is because I understand they are not cross platform and am developing my client to support all the major operating systems.
To summarize:
What is wrong with my log output function? Do you see any way it could be improved?
Should I generally avoid c_strings?
You're getting random garble when passing an std::string to vsnprintf because the format specifier "%s" is that of a C-string - a char*.
std::string is not of type char*, but std::string.c_str() is of type char*. vsnprintf will basically read chars pointed to by the address that it presumes is that of a start of a C-string, up until the NUL character '\0'.
An std::string pushed onto the stack and passed as an argument to vsnprintf is not a pointer to a char, however vsnprintf will just treat these bytes as an address and start reading chars/bytes from this address, causing undefined behaviour.
The printf family of functions are not typesafe, since they rely on a format string and variable argument list, which is why your code will compile but you'll get unexpected results.
Bottom line is the printf family of functions expect a char* when you use the format specifier "%s".
I also think you're confusing C style strings (char[]) with the Microsoft-specific CString class. C style strings won't cause you problems on different platforms at all; the literal "This is a test string!" is a C style string (const char[]).
When calling function with variable parameters you must use simple types. For string you must use c_str(). There's no workaround. MFC's CString is designed so that you can get away with using it directly, but that was Microsoft's decision, and part of their design.
EDIT: As I said when calling function with variable parameters you must use string::c_str(). However, instead of C-like functions with variable parameters you can use something like boost::format() and it's parameter feeding operator %. This also gives you more control over ordering of parameters, which is very handy for i18n.

getline in istream and getline in basic_string

string text;
getline(text.c_str(),256);
1) I am getting an error "error: no matching function for call to 'getline(const char*, int)"
What's wrong in the above since text.c_str() also returns a pointer to array of characters.
If I write like this
char text[256]
cin.getline(text, 256 ,'\n');
it works fine. What's the difference between cin.getline and getline?
2) How come
text string;
getline(cin,text,'\n')
accepts the whole line as the input. Where is the pointer to array of characters in this one?
text.c_str() returns a const char *. You may not use it to modify the contents of the string, in any way. It only exists so that you can pass the string data to old C API functions without having to make a copy. You are not allowed to make changes because there is no way that the string object that holds the data could possibly find out about them, and therefore this would allow you to break the string's invariants.
Furthermore, std::getline accepts completely different parameters. (You would know this if you took two seconds to type 'std::getline' into Google.) The error means exactly what it says: "no matching function for call" means "you can't call the function with these kinds of parameters", because every overload of the function accepts something different (and incompatible).
std::getline accepts these parameters:
A stream. You have to pass this because otherwise it doesn't know where to read from.
A string object to read into. NOT a char buffer.
Optionally, a line delimiter char (same as the stream getline member function).
There is not really any such function as "cin.getline". What you are calling is the member function "getline" of the object "cin" - a global variable that gets defined for you when you #include <iostream>. We normally refer to this according to what class the function is defined in - thus, std::istream::getline.
std::istream::getline accepts these parameters:
A char buffer.
Optionally, a line delimiter char.
It does not need a stream parameter because it is a member function of the stream: it uses whatever stream we called it with.
I don't really get what the questioner is trying to do.
C++ allows function overloading, so the compiler is looking for a free function called getline that matches the parameters you have passed, and no such function exists, nor should it exist (what would getline(const char*, int) do anyway?)
The question has been asked many times why getline(istream&, string&) is a "free" function and not part of the iostream interface. Answers suggested have been that iostream outdates STL or that iostream has no dependent on the basic_string class (anywhere, which is also why opening files is done with raw pointers), and Herb Sutter would commend making getline a free-function because he feels class member functions should be minimal (and std::string has far too many, eg the find functions which could be free ones that use the class).
One thing about that function though is how useful it is as you do not need to pre-allocate a buffer and "guess" how big to make it. (Having said that if you read from a big file into a std::string you could bad_alloc if there are no newlines to be found!).
string::c_str() returns a const char *, not a char *. getline works with a string, so what you want is
string text;
getline(cin, text, '\n');
This version of getline allows the string to grow as much as needed. If you need to limit it to a certain number of characters, you would need to use a vector<char> as in the previous answer.
text.c_str() is an array of const characters. The const means neither you nor any function (including any sort of getline) may write into it.
There's no portable way to use a string as a writeable array of characters. But when necessary, you can use a vector<char> instead:
std::vector<char> buffer(256);
std::size_t len = cin.getline(&buffer[0], buffer.size());
std::string text(&buffer[0], len);
But just using the string overload of getline is probably best here.

Opening a file with std::string

This should be a fairly trivial problem. I'm trying to open an ofstream using a std::string (or std::wstring) and having problems getting this to work without a messy conversion.
std::string path = ".../file.txt";
ofstream output;
output.open(path);
Ideally I don't want to have to convert this by hand or involve c-style char pointers if there's a nicer way of doing this?
In the path string, use two dots instead of three.
Also you may use 'c_str()' method on string to get the underlying C string.
output.open(path.c_str());
this should work:
output.open(path.c_str())
I'm afraid it's simply not possible. You have to use c_str, and yes, it sucks.
Incidentally, using char* also means fstream has no support for Unicode file names... a shame.