2016-11-30 4 views
1

저는 C 프로그램과 약간의 어려움을 겪고 있습니다! 문자열이 회문인지 여부를 확인해야합니다! 비 알파벳 문자에주의를 기울여서는 안되기 때문에 프로그램은이를 회문으로 인식해야합니다! "그는 악마로 살았습니까?" 그것은 내가 지금까지 가지고있는 작업은 다음과 같습니다C 문자열이 Palindrome인지 확인하는 프로그램

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

int main() 
{ 
    char sentence[39]; 
    int left = 0; 
    int right = 40; 

    printf("Enter a message: "); 
    fgets(sentence, 40, stdin); 

    while(1) { 

     while(left < right && !(isalpha(sentence[left]))) 
      left++; 
     while(right > left && !(isalpha(sentence[right]))) 
      right--; 

     if(left >= right) 
      break; 

     else { 

      if(sentence[left] != sentence[right]) { 
       printf("Not a Palindrome"); 
       return 0; 
      } 

      left++; 
      right--; 
     } 
    } 

    printf("Palindrome"); 

    return 0; 
} 

는 항상 인쇄하는 것 : NOT A 회문! 하나 인 경우에도.

+1

처럼 보일 수 있습니다? 'fgets'이 문자열의 끝에'\ n'을 남기고 있다고 생각 했습니까? –

+1

'right == 40'이 초기 값일 때'sentence [right]'는 유효하지 않습니다. – timrau

+2

문자를 대문자 또는 소문자로 변환해야합니다. 'H! = h'. –

답변

1

. 첫째, 배열 색인을 끊지 않고 정의되지 않은 값에 액세스하는 대신 문자열 길이를 사용하고, 세 번째는 대소 문자를 검사합니다.

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

int main() 
{ 
    char sentence[200];        // provide plenty of room 
    int left = 0; 
    int right;          // do not assume the length 

    printf("Enter a message: "); 
    fgets(sentence, sizeof sentence, stdin);  // limit the input 
    right = strlen(sentence);      // now get the length 

    while(1) { 
     while(left < right && !(isalpha(sentence[left]))) 
      left++; 
     while(right > left && !(isalpha(sentence[right]))) 
      right--; 
     if(left >= right) 
      break; 
     else { 
      if(toupper(sentence[left]) != toupper(sentence[right])) { // get case the same 
       printf("Not a Palindrome\n"); 
       return 0; 
      } 
      left++; 
      right--; 
     } 
    } 

    printf("Palindrome\n"); 
    return 0; 
} 

프로그램 세션 :

 
Enter a message: He lived as a devil, eh? 
Palindrome 

Enter a message: palindrome 
Not a Palindrome 
0

당신은 문자열의 끝으로 권리를 초기화해야한다 : 나는 당신의 프로그램에 몇 가지 변경 한

#include <string.h> 

// ... 

    right = strlen(sentence) - 1; 
+1

True이지만 39 바이트 만 저장할 수 있기 때문에'sentence'를 읽는 동안 조금 더 일찍 충돌 할 수도 있지만' fgets (문장, 40, 표준); ' – Gerhardh

+0

맞습니다. 그는 문장의 크기를 재조정하거나 fgets를 업데이트해야합니다. –

1

당신은 입력 된 문장이 회문인지 여부를 확인하는 별도의 함수를 작성할 수 있습니다. 다음 코드

이러한 문

char sentence[39]; 
int left = 0; 
int right = 40; 

printf("Enter a message: "); 
fgets(sentence, 40, stdin); 

정의되지 않은 동작이 발생할 배열 문장은 40 개 문자를 입력하려고하는 동안 만 39 요소를 가지고 있기 때문이다. 또한 입력 된 문자열은 40자를 넘을 수 있습니다. 문자열의 길이를 결정해야합니다.

다음은 해당 기능을 작성하는 방법을 보여주는 데모 프로그램입니다.

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

int is_palindrome(const char *s) 
{ 
    size_t n = strlen(s); 

    const char *first = s, *last = s + n; 

    if (n) 
    { 

     do 
     { 
      while (*first && !isalpha((unsigned char)*first)) ++first; 
      if (first != last) 
      { 
       while (!isalpha((unsigned char)*--last)); 
      } 
     } while (toupper((unsigned char)*first) == 
        toupper((unsigned char)*last) && 
        first != last && 
        ++first != last); 
    } 

    return first == last; 
} 

#define N 100 

int main() 
{ 
    while (1) 
    { 
     char s[N]; 

     printf("Enter a sentence (Enter - exit): "); 

     if (!fgets(s, sizeof(s), stdin) || s[0] == '\n') break; 

     printf("\nThe sentence is%s palindrome.\n\n", 
      is_palindrome(s) ? "" : " not"); 
    } 

    return 0; 
} 

그것의 출력은 당신도 기본적인 printf와 디버깅을 시도해 봤어

Enter a sentence (Enter - exit): He lived as a devil, eh 

The sentence is palindrome. 

Enter a sentence (Enter - exit):