bool fitsKey3(string n) {
int ncheck = str.length(n);
if (ncheck = KEY3) {
return true;
} else {
return false;
}
}
The above function uses a string "n" that is a string given to the function from an input file. I want to write this function that checks the length of this "identifier code" from the input file (it's a drone project), and if the length of the security code is equal to the constant integer "KEY3 (= 50), it returns true. Otherwise, return false.
How do I fix this setup?
= assigns the value of KEY3 to ncheck.
== compares ncheck and KEY3 for equality.
Also, unless you're being paid by lines of code, I'd suggest using the much simpler and clearer form:
return n.length() == KEY3;
(I corrected your usage of the length() member function, since I suppose it was only a typo.)
And as pointed out by Anon Mail, unless you want to make a copy of the string every time you call the function, I'd suggest only passing a reference to it (const because you're not modifying it):
bool fitsKey3(string const& n)
I would write it like this:
bool fitsKey3(string n) {
return n.length() == KEY3;
}
You do two operations:
Get string length by n.length()
Compare the length with a KEY3 (NB: use == to compare)
Related
My function is a simple palindrome algorithm that is supposed to take an input integer (test), turn it into a string (test_s), then reverse that string in a new variable (test_s_reverse) then return true if test_s is equal to test_s_reverse.
bool is_palindrome(int test){
test_s = to_string(test);
test_length = test_s.length();
for (int i=(test_length + 1); i>=0; i--){
test_s_reverse += test_s[i];
}
if (test_s_reverse == test_s){
return true;
}
else {
return false;
}
}
I created a main function to test results and using input 12321 the program returns false, even though cout for test_s_reverse is = 12321 and test_s = 12321.
What am I doing wrong?
You should use test_length - 1 instead of test_lenght + 1, because in the new reversed string you have some extra characters which you can't see if you print them.
The .length() function returns you exactly the number of characters in the string. So you either go with test_length, but you do i>0, or if you go in the loop with i>=0 you go with test_length - 1, so you will be sure that there are no blank characters at the end of new string.
But, if you start with test_length, you will need to edit, since there is no character at test_length position:
test_s_reverse += test_s[i-1];
If you use pure C++ code, it should look like this:
bool is_palindrome(int test){
string test_s = to_string(test);
int test_length = test_s.length();
string test_s_reverse;
for (int i=(test_length); i>0; i--){
test_s_reverse += test_s[i-1];
}
if (test_s_reverse == test_s){
return true;
}
else {
return false;
}
}
If it were up to me, I'd do the job rather differently.
std::string has a constructor to build a string for a pair of iterators. It also supports reverse iterators. As such, you can construct a reversed string a bit more easily like this:
std::string test_s_reversed(test_s.rbegin(), test_s.rend());
...but given how much that simplifies the task, you can boil most of it down to something like this:
bool is_palindrome(std::string const &s) {
return s == std::string(s.rbegin(), s.rend());
}
Implementation for an integer would then be something like this:
bool is_palindrome(int val) {
return is_palindrome(std::to_string(val));
}
This is a homework question so while I'd like usable code what I'm really seeking is insight on how to tackle this problem. I have two sorted arrays in ascending order that I need to combine in a recursive function. It seems like I need to institute the sorting part of a merge sort algorithm. The requirements are that the recursive function can only take the two sorted strings as parameters and it cannot use global or static variables.
I think the psuedocode is:
if the size of the two strings == 0 then return the result string.
compare substr(0,1) of each strings to see which is lesser, and append that to result string
recursively call the function with the new parameters being a substr of the string that appended
My questions are: how do I save a result string if I can't use static variables? I've seen code where a string is defined as = to the return statement of the recursive call. Would that work in this case?
The second question is how to increment the function. I need to call a substr(1,size-1) after the first iteration and then increment that without using static variables.
Here's my attempt to solve the equation WITH static variables (which are not allowed):
static string result="";
static int vv=0;
static int ww=0;
if(v.size()==0 && w.size()==0)
return result;
if(w.size()==0 || v.substr(0,1) <= w.substr(0,1)){
result+=v.substr(0,1);
vv++;
return spliceSortedStrings( v.substr(vv,v.size()-vv) , w);
}
else if(v.size()==0 || w.substr(0,1) > v.substr(0,1)){
result+=w.substr(0,1);
ww++;
return spliceSortedStrings( v , w.substr(ww,w.size()-ww));
}
I'll be appreciative for any guidance.
How about this:
std::string merge(std::string a, std::string b) {
if (a.size() == 0) return b;
if (b.size() == 0) return a;
if (a.back() < b.back()) {
std::string m = merge(a, b.substr(0, b.size()-1));
return m + b.back();
}
else {
std::string m = merge(a.substr(0, a.size()-1), b);
return m + a.back();
}
}
Correctness and termination should be obvious, and I think it should fit the constraints you are given. But I wonder what teacher would pose such a task in C++, for the above code is about as inefficient as it possibly can be.
Im trying to create a recursive function that contains a vector of numbers and has a key, which is the number we are looking for in the vector.
Each time the key is found the function should display a count for how many times the key appears in the vector.
For some reason my recursive function is only returning the number 1 (disregard the 10 I was just testing something)
Here's my code:
int recursive_count(const vector<int>& vec, int key, size_t start){
if (start == vec.size())
return true;
return (vec[start] == key? 23 : key)
&& recursive_count(vec, key, (start+1));
}
int main() {
vector <int> coco;
for (int i = 0; i<10; i++) {
coco.push_back(i);
}
cout << coco.size() << endl;
int j = 6;
cout << recursive_count(coco, j, 0) << endl;
}
Not sure what you are trying to do, but as is - your function will return false (0) if and only if the input key is 0 and it is in the vector. Otherwise it will return 1.
This is because you are basically doing boolean AND operation. The operands are true for all values that are not 0, and the only way to get a 0 - is if it is in the vector - and the key is 0.
So, unless you get a false (0) along the way, the answer to the boolean formula is true, which provides the 1.
EDIT:
If you are trying to do count how many times the key is in vec - do the same thing you did in iterative approach:
Start from 0 (make stop condition return 0; instead of return true;)
Increase by 1 whenever the key is found instead of using operator&&, use the operator+.
(I did not give a direct full answer because it seems like HW, try to follow these hints, and ask if you have more questions).
To me it seems that a recursive function for that is nonsense, but anyway...
Think about the recursion concepts.
What is the break condition? That the current character being checked is not in the string anymore. You got that right.
But the recursion case is wrong. You return some kind of bool (what's with the 23 by the way?
The one recursion round needs to return 1 if the current element equals key, and 0 otherwise.
Then we only need to add up the recursion results, and we're there!
Here's the code
int recursive_count(const vector<int>& vec, int key, size_t start) {
if (start >= vec.size()) {
return 0;
} else {
return
((vec[start] == key) ? 1 : 0) +
recursive_count(vec, key, start+1);
}
}
Since this is even tail-recursion, good compilers will remove the recursion for you by the way, and turn it into its iterative counterpart...
Your recursive_count function always evaluates to a bool
You are either explicitly returning true
if (start == vec.size())
return true;
or returning a boolean compare
return (vec[start] == key? 23 : key) // this term gets evaluated
&& // the term above and below get 'anded', which returns true or false.
recursive_count(vec, key, (start+1)) // this term gets evaluated
It then gets cast to your return type ( int ), meaning you will only ever get 0 or 1 returned.
As per integral promotion rules on cppreference.com
The type bool can be converted to int with the value false becoming
0 and true becoming 1.
With,
if (start == vec.size())
return true;
your function with return type int returns 1
I have the following code which finds the strings that contain no Alphabets. Cases like mynumber123 shall not be recognized and the numberFinder() should return false and case like 123 shall be recognized and numberFinder() shall return true as well as the begin index of the number.
the constructor:
CaddressParser::CaddressParser(string fileName) //constructor
{
m_fileName=fileName;
int length=getLength(m_fileName.c_str());
m_text =fileReader(m_fileName.c_str());
m_length=length;
}
which initializes a string m_text that contains the contents of a text file
Somewhere along the implementation I come across the following code:
for (i;i<m_length;i++)
{
bool UpperCaseBeforeNoFound=false;
if(this->numberFinder (i).second)
{
//do some calculations.
}
}
the numberFinder function is implemented as follows:
pair <int,bool> CaddressParser::numberFinder(int counter)
{
bool noFound=isdigit(m_text[counter]); //number found? -> true
if(noFound)
{
int end=HouseNoDigits(counter);
if(((counter-1)>=0) && ((counter +end-1) <m_length))
{
if((!(isalpha(m_text[counter-1]))) && (!isalpha(m_text[counter+end-1])))
{
return make_pair(counter,noFound); //return index if true
}
}
}
else return make_pair(0,noFound);
}
Now the problem is for a text file containing the following text "he23 Market street London Q12 H13". I get the error mentioned in the headline and the debugger takes me to the line in the which contains :
if(this->numberFinder (i).second)
I can't figure out why this is happening. Please help me figure it out.
If this condition in CaddressParser::numberFinder(int counter) fails:
if (counter - 1 >= 0 && counter + end - 1 < m_length)
the function will exit without returning a value, resulting in undefined behavior.
The complexity of the conditionals in the function isn't helped by the poor formatting (at least as posted in the question).
You might get the behavior you need by removing the else so any 'fall-through' will return the default pair value (but that will depend on if that's the value you want to really return in that scenario):
pair <int,bool> CaddressParser::numberFinder(int counter)
{
bool noFound=isdigit(m_text[counter]); //number found? -> true
if(noFound)
{
// ...
}
return make_pair(0,noFound);
}
Access Violation error is normally due to NULL reference. One of the function that you are calling is trying to access a NULL pointer. Make sure your isdigit function returns true or false, m_text points to an exiting memory location. If not you need to allocate the memory. You should also check if the fileName is NULL.
Given strings s and t compute recursively, if t is contained in s return true.
Example: bool find("Names Richard", "Richard") == true;
I have written the code below, but I'm not sure if its the right way to use recursion in C++; I just learned recursion today in class.
#include <iostream>
using namespace std;
bool find(string s, string t)
{
if (s.empty() || t.empty())
return false;
int find = static_cast<int>(s.find(t));
if (find > 0)
return true;
}
int main()
{
bool b = find("Mississippi", "sip");
string s;
if (b == 1) s = "true";
else
s = "false";
cout << s;
}
If anyone find an error in my code, please tell me so I can fix it or where I can learn/read more about this topic. I need to get ready for a test on recursion on this Wednesday.
The question has changed since I wrote my answer.
My comments are on the code that looked like this (and could recurse)...
#include <iostream>
using namespace std;
bool find(string s, string t)
{
if (s.empty() || t.empty())
return false;
string start = s.substr(0, 2);
if (start == t && find(s.substr(3), t));
return true;
}
int main()
{
bool b = find("Mississippi", "sip");
string s;
if (b == 1) s = "true";
else
s = "false";
cout << s;
}
Watch out for this:
if (start == t && find(s.substr(3), t));
return true;
This does not do what you think it does.
The ; at the end of the if-statement leaves an empty body. Your find() function will return true regardless of the outcome of that test.
I recommend you turn up the warning levels on your compiler to catch this kind of issue before you have to debug it.
As an aside, I find using braces around every code-block, even one-line blocks, helps me avoid this kind of mistake.
There are other errors in your code, too. Removing the magic numbers 2 and 3 from find() will encourage you to think about what they represent and point you on the right path.
How would you expect start == t && find(s.substr(3), t) to work? If you can express an algorithm in plain English (or your native tongue), you have a much higher chance of being able to express it in C++.
Additionally, I recommend adding test cases that should return false (such as find("satsuma", "onion")) to ensure that your code works as well as calls that should return true.
The last piece of advice is stylistic, laying your code out like this will make the boolean expression that you are testing more obvious without resorting to a temporary and comparing to 1:
int main()
{
std::string s;
if (find("Mississippi", "sip"))
{
s = "true";
}
else
{
s = "false";
}
std::cout << s << std::endl;
}
Good luck with your class!
Your recursive function needs 2 things:
Definite conditions of failure and success (may be more than 1)
a call of itself to process a simpler version of the problem (getting closer to the answer).
Here's a quick analysis:
bool find(string s, string t)
{
if (s.empty() || t.empty()) //definite condition of failure. Good
return false;
string start = s.substr(0, 2);
if (start == t && find(s.substr(3), t)); //mixed up definition of success and recursive call
return true;
}
Try this instead:
bool find(string s, string t)
{
if (s.empty() || t.empty()) //definite condition of failure. Done!
return false;
string start = s.substr(0, 2);
if (start == t) //definite condition of success. Done!
return true;
else
return find(s.substr(3), t) //simply the problem and return whatever it finds
}
You're on the right lines - so long as the function calls itself you can say that it's recursive - but even the most simple testing should tell you that your code doesn't work correctly. Change "sip" to "sipx", for example, and it still outputs true. Have you compiled and run this program? Have you tested it with various different inputs?
You are not using recursion. Using std::string::find in your function feels like cheating (this will most likely not earn points).
The only reasonable interpretation of the task is: Check if t is an infix of s without using loops or string functions.
Let's look at the trivial case: Epsilon (the empty word) is an infix of ever word, so if t.empty() holds, you must return true.
Otherwise you have two choices to make:
t might be a prefix of s which is simple to check using recursion; simply check if the first character of t equals the first character of s and call isPrefix with the remainder of the strings. If this returns true, you return true.
Otherwise you pop the first character of s (and not of t) and proceed recursively (calling find this time).
If you follow this recipe (which btw. is easier to implement with char const* than with std::string if you ask me) you get a recursive function that only uses conditionals and no library support.
Note: this is not at all the most efficient implementation, but you didn't ask for efficiency but for a recursive function.