**EDIT: in addition to the mistakes pointed out below, i was mistakenly trying to compile it as a Win32 project, per this error code
1>MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol WinMain@16 >referenced in function __tmainCRTStartup so crisis averted and homework complete. Thank you all very much for your help. hopefully i can similarly pay the community back when i know a thing or two.**
In this assignment we're supposed to use recursion as a technique for determining whether a word qualifies as a palindrome. Although i'm still struggling to become comfortable with it as a problem solving mechanism, this code seems like it should otherwise work. However, the compiler gives me the "not all control paths return a variable" error. Any ideas?
#include<iostream>
#include<fstream>
#include<string开发者_开发百科>
using namespace std;
bool palcheck(string word, int first, int last);
int main()
{
ofstream palindrome, NOTpalindrome;
ifstream fin;
string word;
palindrome.open("palindrontest.txt");
NOTpalindrome.open("notPalindronetest.txt");
fin.open("input5.txt"); //list of palindromes, one per line
if (palindrome.fail() || NOTpalindrome.fail() || fin.fail())
return -1;
while (fin >> word)
{
if (palcheck(word, 0, (word.size()-1)) == true)
palindrome << word << endl;
else
NOTpalindrome << word << endl;
}
palindrome.close();
NOTpalindrome.close();
fin.close();
return 0;
}
bool palcheck(string word, int first, int last)
{
if (first >= last)
return true;
else if (word[first] == word[last])
return palcheck(word, first+1, last-1);
else// (word[first] != word[last])
return false;
}
The error is in your palcheck
function. If the expression in the else if
was true, the function wouldn't return a value.
The following should fix it:
bool palcheck(string word, int first, int last)
{
if (first == last)
return true;
else if (word[first] == word[last])
return palcheck(word, first+1, last-1);
else// ((word[first] != word[last]) || (first > last))
return false;
}
The error is in your palcheck function, you forgot to return the value of the recursed function
bool palcheck(string word, int first, int last)
{
if (first == last)
return true;
else if (word[first] == word[last])
return palcheck(word, first+1, last-1); // <- this return ;)
else// ((word[first] != word[last]) || (first > last))
return false;
}
if (first == last)
needs to be
if (first >= last)
in case there are an even number of letters.
bool palcheck(string word, int first, int last)
{
if (first == last)
return true;
else if (word[first] == word[last])
palcheck(word, first+1, last-1); // <-here
else
return false;
// <-reaches here
}
The problem is marked here
above. When that case is selected, you're not returning anything from the function, which is a problem. You should probably use:
return palcheck(word, first+1, last-1);
精彩评论