我有一个函数 int Reverse(ifstream &inFile, int level)。它应该一次读取一个字符,直到达到某个分隔符。然后该函数以相反的顺序显示这些字符。分隔符返回给调用函数。分隔符不会颠倒。
#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);
}
我已经到了无法真正返回分隔符的地步。似乎并非所有控制路径都返回一个值。如何使函数返回正确的值?谢谢。
最佳答案
如果我没猜错,您希望 Reverse 函数在末尾返回分隔符。 问题是 Reverse 函数不一定返回任何内容,因为如果在此递归级别读取的字符不是分隔符,则最后一个 if 语句的计算结果不会为真。 分隔符不会传回。
您可以通过引入另一个变量来解决这个问题。
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;
}
关于c++ - 使用递归方法反转ifstream输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17783887/