For loop not accessing and performing check - c++

I am having some troubles with one of my for loops not executing correctly. I have stepped through my code to try and see what's going on but it just seems to skip the for loop completely therefore giving the incorrect output.
My for loop looks like this:
for (auto &link : p1links){
if (link->accessTransportType() != type){
continue;
}
if ((p1->accessReference() == link->accessReferenceNumber1() && p2->accessReference() == link->accessReferenceNumber2()) || (p1->accessReference() == link->accessReferenceNumber2() && p2->accessReference() == link->accessReferenceNumber1()))
{
anyPASS = true;
}
}
if (anyPASS){
m_outFile << p1->accessReference() << "," << p2->accessReference() << "," << "PASS" << endl;
return true;
}
else{
m_outFile << p1->accessReference() << "," << p2->accessReference() << "," << "FAIL" << endl;
return true;
break;
}
}
m_outFile << endl;
And these are the methods its trying to access when I say accessTransportType() etc.
class Links
{
public:
Links(int, int, const string&, bool);
~Links();
int accessReferenceNumber1()const{ return referenceNumber1; }
int accessReferenceNumber2()const{ return referenceNumber2; }
string accessTransportType()const{ return transportType; }
bool accessHasBeenSearched()const{ return hasBeenSearched; }
private:
int referenceNumber1 = 0;
int referenceNumber2 = 0;
string transportType = "";
bool hasBeenSearched = false;
};
My output is currently returning the FAIL every time but I am looking to return PASS for my first check and then a FAIL when it does the second check.

Related

C++ indicate Palindrome

I'm pretty new to coding in C++ and need your help. In the code below I want to check for Parlindrome and show the reversed text. So if I run this code, it displays the right reversed words, but dont return them true if checked for parlindrome.
The console shows:
madam0
ada0
ecalevol0
Why the return is always 0?
Thanks for your help!
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text) {
std::string text_reversed;
for(int i = text.length(); i >= 0; i-- ) {
text_reversed += text[i];
std::cout << text[i];
}
if (text_reversed == text) {
return true;
} else {
return false;
}
}
int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}
Your i starts at text.length(), not text.length() - 1.
So, your first text[i] is a null byte (yes, even for std::string, this is guaranteed).
Thus the first character of text_reversed is a "hidden" character that was not present in text, and the two will never match.
std::string reversed_string(const std::string& s)
{
return {s.rbegin(), s.rend()};
}
bool is_palindrome(const std::string& s)
{
return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}
Documentation of std::equal has example of is_palindrome
Your biggest problems there are i>=0 and text[i]. It should be i>0 and text[i-1].
And please simplify that return statement.
#include <iostream>
bool is_palindrome(std::string text) {
std::string text_reversed = "";
for(int i = text.length(); i > 0; i-- ) {
text_reversed += text[i-1];
}
std::cout << text_reversed <<std::endl;
std::cout << text <<std::endl;
return text == text_reversed;
}
int main() {
std::cout << is_palindrome("madam") << std::endl;
std::cout << std::endl;
std::cout << is_palindrome("ada") << std::endl;
std::cout << std::endl;
std::cout << is_palindrome("lovelace") << std::endl;
std::cout << std::endl;
}

Is It Idiomatic To Use C++ Exception Handling Only For "Real" Errors?

I learned about the try/catch block awhile ago. From what I understand, this is used to handle "Real" errors like runtime errors. Instead, I used it to handle incorrect sign in attempts here, even though it's not really needed:
void signIn(std::vector<User>& userVect, int& index, bool& isLoggedIn)
{
std::string userNameSearchKey;
std::string pass;
int passwordRetry = 0;
int userRetry = 0;
bool keepSearching = true;
bool userFound = false;
while (!userFound && userRetry < 3 && userNameSearchKey != "b")
{
try
{
if (userRetry >= 3)
{
throw 2;
}
std::cout << "\nEnter a username, or 'b' to go back" << std::endl;
std::cout << "Username: ";
std::cin >> userNameSearchKey;
if (userNameSearchKey == "b")
{
break;
}
std::cout << "Password: ";
std::cin >> pass;
for (int i = 0; i < userVect.size(); i++)
{
if (userNameSearchKey == userVect[i].getUserName())
{
userFound = true;
if (pass == userVect[i].getPassword())
{
std::cout << "\nWelcome " << userVect[i].getUserName(); // Welcomes the user
index = i; // When this function ends
isLoggedIn = true;
}
else
{
throw 1;
}
}
}
if (!userFound && userNameSearchKey != "b")
{
throw 1;
}
}
catch(int x)
{
if (x == 1)
{
std::cout << "\nError " << x << ": Incorrect username or password." << std::endl;
userRetry++;
if (userRetry >= 3)
{
std::cout << "Too many incorrect attempts. Going back to the main menu." << std::endl;
}
}
}
}
}
Please keep in mind that the code is just an illustration of the point I'm making: The function works fine and it does its job, but I could also get the same effect without try/catch and throw. Is it more idiomatic to reserve exception handling for actual errors?

Negative value not being added to Array

Problem
I have 2 arrays, one for positive numbers, one for negative numbers. For some reason, if the first number to be added is a negative number, it creates the array space to add the number yet the number inserted will always be 0.
Code for adding
Here is my add method, it determines if the value is negative or positive and adds the value to the appropriate array:
bool MyClass::addInt(int valueToBeInserted){
if (valueToBeInserted >= 0){
if (posArrayIterator >= sizeOfMyArray){
return false;
} else {
cout << "added " << valueToBeInserted << "\n" << endl;
myPArray[posArrayIterator] = valueToBeInserted;
posArrayIterator ++;
return true;
}
} else {
if (negArrayIterator >= sizeOfMyArray){
return false;
} else {
cout << "added " << valueToBeInserted << "\n" << endl;
myNarray[negArrayIterator] = valueToBeInserted;
negArrayIterator ++;
return true;
}
}
}
Output
With the following test:
b.addInt(-1);
b.addInt(-3);
b.addInt(-9);
The expected output would be
[-1, -3, -9]
but output is
[-3, -9, 0].
Any help is much appreciated.
Since you are not posting the whole class I can only guess where the problem is.
1) Are posArrayIterator and negArrayIterator initialized to 0? They should be!
2) What is a value of sizeOfMyArray?
There is nothing wrong with your bool MyClass::addInt(int valueToBeInserted)
See example below:
class MyClass
{
private:
int sizeOfMyArray;
int posArrayIterator;
int negArrayIterator;
int myNarray[20];
int myPArray[20];
public:
MyClass(){
sizeOfMyArray = 20;
posArrayIterator = 0;
negArrayIterator = 0;
};
bool addInt(int value);
void printNArray()
{
cout << "[ ";
for (int i=0; i<negArrayIterator; i++)
{
cout << myNarray[i];
if ( (i+1) < negArrayIterator )
{
cout << ", ";
}
}
cout << "]";
}
};
bool MyClass::addInt(int valueToBeInserted){
if (valueToBeInserted >= 0){
if (posArrayIterator >= sizeOfMyArray){
return false;
} else {
cout << "added " << valueToBeInserted << "\n" << endl;
myPArray[posArrayIterator] = valueToBeInserted;
posArrayIterator ++;
return true;
}
} else {
if (negArrayIterator >= sizeOfMyArray){
return false;
}
else {
cout << "added " << valueToBeInserted << "\n" << endl;
myNarray[negArrayIterator] = valueToBeInserted;
negArrayIterator ++;
return true;
}
}
}
int main()
{
MyClass b;
b.addInt(-1);
b.addInt(-3);
b.addInt(-9);
b.printNArray();
return 0;
}
Output:
added -1
added -3
added -9
[ -1, -3, -9]

c++ scandir is filling my memory up

I use a function I implemented in my class:
bool MyClass::getNextFile(string& s_first_file, const char* c_path_data){
//string s_first_file = "";
struct dirent **namelist;
string s_file_actual = "";
int n;
int i=0;
n = scandir(c_path_data, &namelist, dataFilter, alphasort);
if (n < 0){
//perror("scandir");
return false;
}else{
while (i<n) {
s_file_actual = namelist[i++]->d_name;
if(i==1){
cout << "get file " << s_file_actual << "..." << endl;
s_first_file = s_file_actual;
}
}
free(namelist[i-1]);
return true;
}
}
In my c++ programm I use the following:
...
MyClass myc;
...
int main(){
while(myc.getNextFile(s_first_file, c_path_data)){
s_first_file << endl;
}
return 1;
}
What happens is that my ram memory get fuller and fuller as long as the function is called every time again.
If I put the code directly it in the main It searches the next first occouring file and don't collect that much memory.
Any hint what I am missing here?
Thank you very much.
You should do something like this;
while (i<n)
{
s_file_actual = namelist[i++]->d_name;
if (i==1)
{
cout << "get file " << s_file_actual << "..." << endl;
s_first_file = s_file_actual;
}
free(namelist[i-1]);
}
free(namelist);
return true;
while (i<n) {
s_file_actual = namelist[i++]->d_name;
if (i==1) {
cout << "get file " << s_file_actual << "..." << endl;
s_first_file = s_file_actual;
}
}
free(namelist[i-1]);
return true;
Whoops!
I'm not sure how it happened, but you put your free in the wrong place and forgot the other one.
Per the manpage, you need to free(namelist[i-1]) inside the loop … and perform a free(namelist) at the end.

commenting out cout statement causes different (and incorrect) output

I have never experienced anything like this. I was using a cout statement to help me debug a small program, and once I was satisfied with my code I commented out the cout. Now, the code no longer works. Below is the code with the cout commented out.
The intent of this program is to test the two hard coded boolean two dimensional arrays for having an odd number of true statements on each row. Thus, the first array should return true and the second array should return false. With the cout statement commented out both instead return false.
#include <iostream>
using namespace std;
template <size_t size_y>
bool findEvenDegrees(bool mapArray[][size_y])
{
bool returnValue;
for (int x=0; x<size_y; x++)
{
int result = 0;
for (int y=0; y<size_y; y++)
{
result = result + mapArray[x][y];
//the line below causes the problem
cout << mapArray[x][y] << "\t" << result << "\t" << x << endl;
}
if (result%2 == 1)
{
returnValue = false;
break;
}
}
if (returnValue== false)
{
return returnValue;
}
else
{
return true;
}
}
int main()
{
bool array1[][6] =
{
{false,true,true,false,false,false},
{true,false,false,true,false,false},
{true,false,false,true,false,false},
{false,true,true,false,true,true},
{false,false,false,true,false,true},
{false,false,false,true,true,false}
};
bool array2[][8] =
{
{false,true,true,false,false,false,false,false},
{true,false,false,true,false,false,false,false},
{true,false,false,true,false,false,false,false},
{false,true,true,false,true,false,false,false},
{false,false,false,true,false,true,true,false},
{false,false,false,false,false,true,false,true},
{false,false,false,false,true,false,false,true},
{false,false,false,false,false,true,true,false}
};
bool answer1 = findEvenDegrees(array1);
bool answer2 = findEvenDegrees(array2);
if (answer1 == true)
{
cout << "Array 1 has a even degree for every switch." << endl;
}
else
{
cout << "Array 1 has a odd degree for at least one switch." << endl;
}
if (answer2 == true)
{
cout << "Array 2 has a even degree for every switch.";
}
else
{
cout << "Array 2 has a odd degree for at least one switch.";
}
return 0;
}
You never initialize returnValue. If it happens to start out as false it will stay that way and the function will return false.
First, I cleaned up your code a little, and arrived at:
#include <iostream>
template <size_t S>
bool findEvenDegrees(bool (&themap)[S][S]) {
for( bool(&row)[S]: themap ) {
bool is_degree_odd = false;
for( auto col: row )
is_degree_odd ^= col;
if( is_degree_odd )
return false;
}
return true;
}
int main()
{
using std::cout;
using std::endl;
bool array1[6][6] = {
{false,true,true,false,false,false},
{true,false,false,true,false,false},
{true,false,false,true,false,false},
{false,true,true,false,true,true},
{false,false,false,true,false,true},
{false,false,false,true,true,false}
};
cout << "Array 1 has an "
<< (findEvenDegrees(array1) ? "even degree for every" : "odd degree for at least one")
<< " switch." << endl;
bool array2[8][8]= {
{false,true,true,false,false,false,false,false},
{true,false,false,true,false,false,false,false},
{true,false,false,true,false,false,false,false},
{false,true,true,false,true,false,false,false},
{false,false,false,true,false,true,true,false},
{false,false,false,false,false,true,false,true},
{false,false,false,false,true,false,false,true},
{false,false,false,false,false,true,true,false}
};
cout << "Array 2 has an "
<< (findEvenDegrees(array2) ? "even degree for every" : "odd degree for at least one")
<< " switch." << endl;
return 0;
}
In the process of cleaning it up, I eliminated the if(result%2 == 1) { resultValue = true; break; }, by effectively returning when I found the first odd-degree row. As I eliminated the resultValue variable, I also killed the "unitialized" bug mentioned by #sth.