2015-09-20 3 views
-1

Я новичок в программировании на языке C. У меня вопрос, как закончить цикл в окнах.EOF AND GETCHAR до конца цикла

#include<stdio.h> 
#include<conio.h> 

int main() { 
    printf("enter ur palindrome"); 
    int i[100], c, d = 0, n = 0; 

    c = getchar(); 
    while (c != '\n') { 
     i[d] = c; 
     d++; 
    } 
loop: 
    while (d != 0) { 
     if ((i[0 + n] != i[d - n])) { 
      n++; 
      goto loop; 
     } 

     printf("this is not a palindrome"); 

     break; 
    } 
    printf("this is a palindrome"); 

    return (0); 
} 

Я Пытались ПОЧТИ ВСЕ CTRL + Z, CTRL + C, CTRL + D, ЗАМЕНА '\ п' С EOF и многое другое дело. Ничто не сработало для меня. Я использую CodeBlocks в Windows 10. Есть ли другой способ записи такого типа программы, кроме getchar и eof.

+0

использования при + возвращение. –

+0

@ ameyCU while loop не завершается –

+0

@ Atomic_alarm как можно if + retrun. может у plzz объяснить –

ответ

0

Вместо использования goto , используйте continue;, чтобы повторить цикл.

Однако, существует ряд других проблем с размещенным кодом.

The array `int i[100]` is never terminated with a NUL byte ('\0') 
An array of char not int should be used. 
this loop: `while (d != 0) will never exit, 
    because (if the loop is ever entered) 
    the `d` variable is never changed within the loop 

Вот мой Рекомендованный код:

нюанса: не тщательно протестированы

#include <stdio.h> 
//#include<conio.h> <-- not used, so do not include 
#include <string.h> 

#define MAX_LENGTH (100) 

int main(void) 
{ 
    int d; 
    int n; 
    char i[MAX_LENGTH]; 

    printf("enter ur palindrome\n"); // <-- \n so will immediately print 

    if (NULL != fgets(i, MAX_LENGTH, stdin)) 
    { 
     if(strlen("\n") < strlen(i)) 
     { // then, some string entered 

      // remove any trailing '\n' 
      char *newline = strstr(i, "\n"); 
      if(newline) 
      { // then '\n' found 
       *newline = '\0'; 
      } // end if 

      d = strlen(i); 
      for(n=0; (d-n) >= n; n++) 
      { 

       if(i[0 + n] != i[d - n]) 
       { // then no match 
        printf("this is not a palindrome"); 
        break; 
       } // end if 
      } // end for 

      if((d-n) < n) 
      { // then palindrome 
       printf("this is a palindrome"); 
      } // end if 
     } 

     else 
     { 
      printf("nothing entered\n"); 
     } // end if 
    } // end if 

    return (0); 
} // end function: main 
0

вы, вероятно, хотите, чтобы взглянуть на этот раздел снова

c=getchar(); 
    while(c!= '\n') // Value of c never altered, hence it'll never break 
    { i[d]=c; 
    d++; 
    } 

и да, другой цикл

loop: // not required 
    while ( d!=0 ) // can't see change in d within this body, is it n ? 
    { 
    if((i[0+n] != i[d-n])) 
    { 
     n++; 
     goto loop; // not required 
     continue; //will do 
    } 
    printf("this is not a palindrome"); 
    break; 
} 

и вы действительно получите дополнительное сообщение о том,

this is a palindrome 

после печати

this is a not palindrome 

, который, я полагаю, не то, что вы хотите.

+0

ameycu Я новичок в c :) –

+0

@azamiftikhar Да, я ценю ваши усилия, но моя мысль тщательно продумывает алгоритм перед кодированием, чтобы вам пришлось делать меньше изменений, необходимых после кодирования. Извините, если это звучит суровым, я не хотел. – ameyCU

+0

спасибо ameycu и kkk за ур ценные комментарии –

0

В этом цикле вы должны снова прочитать следующий символ так нужно добавить getchar() в этом цикле

c=getchar(); 
    while(c!= '\n') 
    { 
    i[d]=c; 
    d++; 
    c=getchar(); 
    } 
0

Вот другой способ, чтобы написать этот код

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


int main() 
{ 
    char *word; 
    int i; 
    int n; 

    printf("enter ur palindrome"); 
    scanf("%[^\n]", word);      // reads input all the way to the new line 
    n = strlen(word); 

    for (i = 0; i < n; i++) { 
     if (word[ i ] != word[ n-1 - i ]) { 
      break; /* for */ 
     } 
    } 
    if (i == n) { 
     printf("This is a palindrome"); 
    } else { 
     printf("This is not a palindrome"); 
    } 

    return 0; 
} 
+0

1) 'word' не имеет памяти для символов - это неинициализированный указатель! 2) 'scanf ("% [^ \ n] ", word);' не может ничего сканировать в 'word', если ввод начинается с' '\ n''. – chux

Смежные вопросы