0

I have a class that have only one attribute (a char* str) because I want to have a Mystring class that mostly works with cstyle strings. I paste just this code because I have a curiosity that can help me very much in a future program and I can't find the answer anywhere.

There is a posibility for me to modify this code (I don't know about exceptions yet and things like that) so that I can get the full string? I think it's something about the null character but I really don't get it... I just learned to overload operators but I can't figure out how to get a full string instead of a single word...

std::istream& operator>>(std::istream& is, Mystring& source) {
    char* tempstr = new char[1206];
    is >> tempstr;
    source = Mystring{ tempstr };
    delete[] tempstr;

    return is;
}

Thank you for your help and time!

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    What do you mean by _full string_? If you enter a space within your string (e.g. "hello world") then only up until the space is used (i.e. "hello"). If you want the full like, you should use `std::getline` – ChrisMM Jul 24 '20 at 22:48
  • Yes, exactly, I want the full string like you said, including spaces. How do I modify it in my curent program? How it should look like to support this? –  Jul 24 '20 at 22:49
  • Where does the number `1206` come from? That's completely random. Unless you clone that data, `delete` will invalidate that pointer and all you have left is sadness and undefined behaviour. – tadman Jul 24 '20 at 23:28
  • 1
    Your code shows an extraction operator (extract data from a stream) not an insertion operator (insert data into a stream). In any event, extraction operators that read strings, by convention, stop when they first encounter whitespace - doing otherwise will confuse users of your class. If you want to extract multiple strings separated by whitespace, don't implement an `operator>>()`. Implement a separate operation (e.g. a member function of `MyString`) to do the job of reading multiple strings separated by whitespace (and presumably you also need to define when reading stops). – Peter Jul 25 '20 at 00:29
  • Yep, I solved it now. With your replies I mostly put them head to head and solved it finally. Thanks! –  Jul 25 '20 at 21:34

0 Answers0