Let me start by stating that I am working on homework but I am not looking for code because I won't learn that way. I am a beginner with no access to a mentor or tutor to guide me. The following code is suppose to take a given string and return true if it ends in "ty" or false for anything else. It seems pretty easy but I am having a lot of trouble in every aspect it is calling for (functions, strings, arrays, maybe even the if statements and loops). I have been looking for postings with some similarities to my program to no avail. I've tried piecing together codes I've found that are not it but are close and still the same result. I beg for your assistance and patience and hope you have a great (your current time of day), regardless of your response.
//Function 1:
//Given a string, return true if the last two letters are 'ty'.
#include <iostream>
usingnamespace std;
constint SIZE = 21; //Array size
char line[SIZE]; //Location of input
int count = 0; // counter variable
bool firstFunction() // name of bool function
{
cout << "Enter a string of " << (SIZE - 1) << " or less characters:\n"; // prompt instructing user
cin.getline(line, SIZE); // input from user
for (count = 0; count < SIZE; count++)
{
if (line[count] != '\0' && line[(count - 1)] == 'y' && line[(count - 2)] == 't')
returntrue;
returnfalse;
}
}
int main()
{
firstFunction();
return 0;
}
Regardless of what I enter for input, (hefty, foul), my program returns 0. I am pretty sure there are more errors here than not, but if you could at least guide me as to where and why, I would be most grateful.
Your test has two issues:
1. It matches "ty" that is NOT at end of string.
2. It dereferences out of range, when count<2
3. Array content beyond the string is undefined, and could thus contain "ty\0".
No matter what the condition does, your loop (and function) ends on its first iteration.
Your function returns a value, but your main() deos not do anything with it.
Proposal:
1. Find out the end of the string that the user gives.
2. Now you can look at the two last characters without a loop.