I am creating my own String class, just to practice, but I have little experience in overloading operators.
I would like that my string can have also spaces (and possible I can manage dynamically what the user inputs?)
I have seen something similar:
1 2 3 4 5 6 7 8 9
std::istream& operator>>(std::istream& in, String& str)
{
if(in != NULL)//Is this necessary?
{
in >> std::setw(str.length-1) >> str.charPointer;
str.charPointer[str.length] = '\0';//This?
}
return in;
}
Another (stupid) thing: what is the best: nullptr or NULL or 0? What are the best situations to use one rather than the other?
No. (a) references cannot be null naturally (and it takes a dedicated user to amke one artificially) and (b) you cannot check for null that way. This line does not do what you probably think. What actually happens is way more complex and includes several implicit casts (and probably will not compile in C++11).
Exact operator implementation would depend on your string internal implementation (GCC implementation of std::string reads data in chunks of 128 charactes and appends it to the string by callig .appemd() member function)
I would go with the same by allocating local char array, calling .getline() member function on it and appending result to your string until stream either fails, endline is found
Another (stupid) thing
If you are using C++11 always use nullptr. If you are using older version of C++ or C, always use NULL. 0 is unportable.