user2606232
user2606232

Reputation: 3

Reverse ifstream input using recursive method

I have a function int Reverse(ifstream &inFile, int level). It is supposed to read one character at a time until certain separator is reached. Then the function displays those characters in reverse order. The separator is returned to the calling function. Separators are not reversed.

#include <fstream>
#include <cctype>
#include <iostream>

using namespace std;

inline bool checkSeparator(int someValue)
{
   return(isspace(someValue) || someValue == (int)',' || someValue == (int)':' ||     someValue == (int)';' ||
  someValue == (int)'.' || someValue == (int)'?' || someValue == (int)'!' || someValue == EOF);
}

int Reverse(ifstream &inFile, int level)
{
   int input = inFile.get();

   if (!checkSeparator(input))
      Reverse(inFile, ++level);

   --level;

   if (level == 1)
      input = toupper(input);

   if (!checkSeparator(input))
      cout.put(input);

   if (checkSeparator(input))
      return(input);
}

I got to the point that I couldn't really return the separator. It seems not all control paths return a value. How can I make the function return the correct value? Thanks.

Upvotes: 0

Views: 447

Answers (1)

Andreas Hehn
Andreas Hehn

Reputation: 138

If I got it correct you want the Reverse function to return the separator at the end. The problem is the Reverse function doesn't necessarily return anything, since the last if statement doesn't evaluate to true if the character read at this recursion level is not a separator. The separator is not propagated back.

You can fix this by introducing another variable.

int Reverse(ifstream &inFile, int level)
{
   int input = inFile.get();
   int separator = 0;
   if (checkSeparator(input))
       return input;
   else
       separator = Reverse(inFile, ++level);
   ...
   // remove the last if
   return separator;
}

Upvotes: 2

Related Questions