dimanche 1 juillet 2018

String check always returns false Palidrome

I am writing a program to check if an input string from the user is a palindrome My program always returns false even if the string is a known palindrome. I think my problem lies in the PalindromeChecker function in that this is what always sets the answer variable in the main function to false. However I am unsure as to why this is always the case. Any help finding my problem would be appreciated.

#include "stdafx.h"
#include <iostream>
#include <String>

using namespace std;

char ReadPalIn(string Pal, int len)//converts the string into a char array
{
    char PalIn[100];
    if (len > 100)
    {
        cout << "ERROR: Palindrome possibliity too big" << endl;
        system("Pause");
    }
    else
    {
        for (int i = 0; i < len; i++)
        {
            PalIn[i] = Pal[i];
        }
    }
    return *PalIn;
}

bool PalindromeChecker(char Pal[],int start, int end)//checks recursively if a string is a palidrome
{
    if (start == end)
    {
        return true; //since there is only one character
    }
    else if (Pal[start] != Pal[end])
    {
        //cout << "hi" << endl;
        return false;//since that will be the case that decides when something stops being a palidrome
    }
    else if (start < end + 1)
    {
        //cout << "hi" << endl;
        return PalindromeChecker(Pal, start++, end--);//since we checked both the first and last characters of the char array for palandrominess. <- word of the year?
    }
    else
    {
        return true;//base case is the string is a palindrome
    }
}

int main()//test if a word is a palidrome using the functions
{
    int lengthOfPal = 0;
    string PalInd = "abba";
    bool Answer = true;
    cout << "Hello what string would you like to check?" << endl;
    getline(cin, PalInd);
    lengthOfPal = PalInd.length();
    cout << "You input is: " << PalInd << endl;
    cout << "Its Length is: " << lengthOfPal << endl;
    system("Pause");
    char PalIn[100] = { ReadPalIn(PalInd, lengthOfPal) };

    Answer = PalindromeChecker(PalIn, 0, lengthOfPal);
    if (Answer == true)
    {
        cout << PalInd << ": is a palidrome" << endl;
        system("Pause");
    }
    else if(Answer == false)
    {
        //cout << "hi" << endl;
        cout << PalInd << ": is not a palidrome" << endl;
        system("Pause");
    }
    return 0;
}

What is C++ equivalent of “%-[width]s” for cout stream? [duplicate]

This question already has an answer here:

Here’s what i normal do in c code:

Printf(“%-40s = 42\n”, “life”)

“Life”will be left justified with spaces padding on right...

How can I accomplish the same thing in c++ cout style code?

(Sorry... I’ve been dragging my feet for years when it comes to use using cout over printf)

template function overload in non-template class using SFINAE

TL;DR

A couple of templatized and overloaded non-templatized member functions in a non-templatized class should all end up routing through the same member function to perform the actual work. All the overloads and templatizations are done to convert the "data buffer" into gsl::span<std::byte> type (essentially a close relative to std::array<std::byte, N> from the Guidelines Support Library)


Wall of code

#include <array>
#include <cstdlib>
#include <iostream>
#pragma warning(push)
#pragma warning(disable: 4996)
#include <gsl.h>
#pragma warning(pop)

// convert PoD into "memory buffer" for physical I/O
// ignore endianness and padding/alignments for this example
template<class T> gsl::span<std::byte> byte_span(T& _x) {
    return { reinterpret_cast<std::byte*>(&_x), sizeof(T) };
}

// implementation of physical I/O (not a functor, but tempting)
struct A {
    enum class E1 : uint8_t { v1 = 10, v2, v3, v4 };
    bool f(uint8_t _i1, gsl::span<std::byte> _buf = {});    // a - "in the end" they all call here
    bool f(E1 _i1, gsl::span<std::byte> _buf = {});         // b
    template<typename T, typename = std::enable_if_t< std::is_integral<T>::value > >
        bool f(uint8_t _i1, T& _val);                       // c
    template<typename T, typename = std::enable_if_t< std::is_integral<T>::value > >
        bool f(E1 _i1, T& _val);                            // d
};

bool A::f(uint8_t _i1, gsl::span<std::byte> _buf)
{
    std::cout << "f() uint8_t{" << (int)_i1 << "} with " << _buf.size() << " elements\n";
    return true;
}

bool A::f(E1 _i1, gsl::span<std::byte> _buf)
{
    std::cout << "f() E1{" << (int)_i1 << "} with " << _buf.size() << " elements\n\t";
    return f((uint8_t)_i1, _buf);
}

template<class T, typename>
bool A::f(uint8_t _i1, T& _val)
{
    std::cout << "template uint8_t\n\t";
    return f(_i1, byte_span(_val));
}

template<class T, typename>
bool A::f(E1 _i1, T& _val)
{
    std::cout << "template E1\n\t";
    return f(_i1, byte_span(_val));
}

int main(){
    A a = {};
    std::array<std::byte, 1> buf;
    long i = 2;

    // regular function overloads
    a.f(1, buf);
    a.f(A::E1::v1, buf);

    // template overloads
    a.f(2, i);
    a.f(A::E1::v2, i);

    struct S { short i; };
    // issue
    //S s;
    //a.f(3, s);
    //a.f(A::E1::v3, s);

    //// bonus - should use non-template overrides
    //S sv[2] = {};
    //a.f(5, sv);
    //a.f(A::E1::v1, sv);
}

Details

The struct S is a PoD and it is tempting to change the template's enable_if to use the std::is_trivial or std::is_standard_layout. Unfortunately both these solutions "grab too much" and end up matching std::array (even if they do fix the compilation error of the //issue block).

The solution I have right now looks like a dead-end as my gut feeling is to start adding more template parameters and it seem to be getting very hairy very soon :(

Question

My goal is to achieve the following: use the class A's bool f() member function without too much syntactic overhead for any PoD (possibly including C arrays - see "bonus" in code) as shown in the body of main() and no runtime function call overhead for types that are auto-convertible to gsl::span (like std::array and std::vector).

If this is not achievable I'd like to know why.

I'm on MSVC 2017 with C++17 enabled.

invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'

#include<iostream>

class A {

    public:
        void fun() { fun2(); }
        ~A() = default;
    protected:
        virtual void fun2() = 0 ;
};

class B : public A {
    protected:
        virtual void fun2() { std::cout<<"Hiiii";} 
};

class X {
    public:
        X(A& a) {
           a.fun();
        }  
};

class Y {

    public:
        Y( int x ) : val(x), x(B())
        {}
    private:
        int val;
        X x;
 };


 int main() {

    Y y(5);
 }

Am not able to figure out why am getting following compilation error:

prog.cpp: In constructor 'Y::Y(int)': prog.cpp:30:32: error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A' Y( int x ) : val(x), x(B()) ^ prog.cpp:21:7: note: initializing argument 1 of 'X::X(A&)' X(A& a) { ^

Usage of Uniform Initialization Syntax

If I have a class

class Foo
{
public:
    Foo();
    Foo(int bar);

private:
    int m_bar;
}

What is the difference between these two ways to initialize it's member

Foo::Foo(int bar):
    m_bar(bar)
{

}

Foo::Foo(int bar):
    m_bar{ bar }
{

}

I was told on a code review to use Uniform Initialization Syntax, i.e. brace initialization. Is there a difference in this case? Or is it just a style preference?

C++: When using templates to support functor as arguments, what qualifier should I use?

Consider this code:

template<class F>
void foo1(F f) { f(); }

template<class F>
void foo2(F const& f) { f(); }

template<class F>
void foo3(F&& f) { f(); }

Which version of foo should I use? foo1 is what I see most "in the wild" but I fear that it might introduce copies that I don't want. I have a custom functor that is kind of heavy to copy so I would like to avoid that. Currently I'm leaning towards foo3 (as foo2 would disallow mutating functors) but I'm unsure about the implications.

I'm targeting C++11.

Recursive alias template (C++11)

I'm creating an adjacency list to modelize an oriented weighted graph, and i'd like to know if recursive alias templates are possibe. I've tried something like this

template<class edge_data>
using graph_test = std::set<std::map<std::set<graph_test>::const_pointer, edge_data>>;

(each entry of the set is a map, and each map represents a vertex. each entry of the maps are edges: keys are pointers to other vertices, values are weight. the pointers are not invalidated on insertion)

This produces an error : 'graph_test': undeclared identifier.

I know I could use std::any to avoid this problem, but it look a bit 'dangerous', even if I know what I'm doing.

Do yu have any suggestions/ideas that might solve this problem ?