Search code examples
c++stringstream

recursive call should output reverse string


Hello together

void rev_out(istream& is){
char a;
is >> a;
if(a!='g')rev_out(is);
cout << a;
}


int main()
{
stringstream is("abcdefg");
rev_out(is);
return 0;   
}

now the Output is gfedcba, but i have a problem. I`d like to give an universally valid if-statement like "stop after the string is read completely". So if there is any stream you don`t know, the function knows when it has to stop. Is there a possibility without counting the string-elements first?

Thanks for your help!


Solution

  • Just stop when you can't read any more:

    void rev_out(istream& is){
        char a;
        if (is >> a)          // If we could read a character...
        {
            rev_out(is);      // ... keep reversing ...
            cout << a;        // ... and print the character.
        }
        // Otherwise, nothing happens.
    }