-1

I have a custom String class that contains a char array, and I need to overload the >> operator for this class. For the life of me I can't figure out how to do two things.

1 - Read the user input until a ; is reached

2 - Include whitespace from user input

I cannot use namespace or c++'s built-in string. Unfortunately that rules out the use of getline and any of the convenient find functions (I think it does, anyway?). Some things I have tried:

std::istream& operator >> (std::istream& output, String& input) {
    output >> input.str;
return output;}

This works but only up until the first whitespace, after which point it stops reading the user input.

std::istream& operator >> (std::istream& output, String& input) {
while (output != ';') {
    output >> input.str;
}
return output;}

An istream I guess isn't equivalent to the user input so you cannot compare it to a char like I tried to in my while loop.

So, my questions are, how does one read input until a specified character is encountered, and how does one include all whitespace when using >> ?

nwp
  • 9,623
  • 5
  • 38
  • 68
  • Possible duplicate of [How can I read and parse CSV files in C++?](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – user0042 Oct 10 '17 at 21:06
  • This isn't the problem, but it's unusual to have an **input** stream named `output`. – Pete Becker Oct 10 '17 at 21:18
  • Read one character at a time, and test if it matches the specific character. – Barmar Oct 10 '17 at 21:43

1 Answers1

0

The global operator>> for string/character input stops reading when it encounters whitespace, so it is not worthwhile to implement your custom operator>> in terms of the global operator>>.

You ruled out use of std::getline(), but you can use std::istream::getline() instead. Like std::getline(), it also has an optional delim parameter (the default is '\n'), and will read characters - including whitespace - until the delimiter or EOF is reached.

std::istream& operator >> (std::istream& input, String& output)
{
    return input.getline(output.str, yourmaxstrsize, ';');
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770