Home > Net >  Calling a void function?
Calling a void function?

Time:10-04

I'm trying to write a program that can recognize a palindrome.

I've made a function for recognizing if it is a palindrome and used it in main successfully.

However, I also want to remove any spaces or numbers or special characters as those could interfere with recognizing it as one.

I've tried calling on it in main with inputstring(isalphabet) but it won't compile at all. Also tried changing isalphabet to char instead of void, and giving it return inputstring but it won't work. Any and all suggestions appreciated

#include <stdio.h>

int isPalindrome(char inputString[]);

int main() {
    char inputString[100];
   
    int ret;
    scanf("%s", inputString);
    

    ret = isPalindrome(inputString);

    
    printf("%d", ret);
}


int isPalindrome(char inputString[])
{
    int count = 0;
    int result;
    while (inputString[count] != '\0') {
        count  ;
    }

   
    char stcp[100];
    int i = count, j = 0;

    while (i != 0) stcp[j  ] = inputString[--i];
    stcp[j] = 0;

    if (strcmp(inputString, stcp) == 0)
    {
        result = 1;
    }

    else
    {
        result = 0;
    }

    return result;
    
}

void isalphabet(char inputString[], char nystring[])
{
    int count, i, ny_i = 0;
    count = strlen(inputString);

    for (i = 0; i < count; i  )
    {
        if (isalpha(inputString[i]) != 0)
        {
            nystring[ny_i] = inputString[i];
            ny_i  ;
        }
        nystring[ny_i] = '\0';
          
    }
}

CodePudding user response:

Using the auxiliary array with the magic number 100

char stcp[100];

is a bad idea. The user can pass to the function a string of an arbitrary length that can be greater than 100.

It seems what you need is something like the following.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int isPalindrome( const char *s, int cmp( int ) )
{
    int palindrome = 1;
    
    const char *p =  s   strlen( s );
    
    while ( palindrome && s < p )
    {
        if ( !cmp( ( unsigned char )*s ) )
        {
              s;
        }
        else if ( !cmp( ( unsigned char )*--p ) )
        {
            ;
        }
        else
        {
            palindrome = *s   == *p;    
        }
    }
    
    return palindrome;
}

int main(void) 
{
    printf( "%d\n", isPalindrome( "1a12b123c1234b12345a123456", isalpha ) );
    printf( "%d\n", isPalindrome( "1a2bc3def2gh1i", isdigit ) );
    
    return 0;
}

The program output is

1
1
  • Related