Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c - Check palindrome input if string or int

Hi everyone I want check input(char or int) polindrome or not but I can't do this. Can you help me ? I have error message

"invalid conversation char to char*"

I think this is a simple problem but I couldn't solve it already. Thank you for your help.

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

int main()
{
    int r,sum=0,temp;
    char a;
    char *b = &a;
    printf("Enter a string or number
");
    scanf("%c", &a);

    if ( isalpha( a ) )
    {
        b = a;
        strrev(b);
        if (strcmp(a, b) == 0)  
            printf("The string is a palindrome.
");
        else    
            printf("The string isn't a palindrome.
");
    
    }
    else if ( isdigit( a ) )
    {
        temp=a;    
        while(a>0)    
        {    
          r=a%10;    
          sum=(sum*10)+r;    
          a=a/10;    
        }    
        if(temp==sum)    
          printf("palindrome number ");    
        else    
          printf("not palindrome");   
        }    
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you mentioned that you are a student and want to learn C, I am not going to write a code but will try to point you into the right direction.

To solve this, you need:

  1. Get a alphanumeric string
  2. Check if it's a palindrome (you have several options there)

First of all, to get a string, you have in your code:

char a;
scanf("%c", &a);

A hint: this is only getting you one character. To get a string, you first need to allocate an array instead of one single char, and then use scanf with a different argument, not %c.

This part of the task is completely independent of the second part. I recommend first to make sure that this part works before proceeding further. You can do it by getting a string and then immediately printing it. This way you can see what you are actually dealing with.

Once you have your string, proceed with analyzing it. You could revert it and then compare to original (that's what your code is suggesting), but it's probably easier to do something like this:

  1. Find string length
  2. Compare each symbol in the string with its symmetrical counterpart. For example, if string length is 10, you'll need to compare symbol #0 with symbol #9, symbol #1 with symbol #8 etc. etc. Hint: you'll need to use a loop here.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...