사용자가 입력 한 문자열이 회문인지 확인하고 싶습니다. 함수를 사용하지 않고이 문제를 수행했지만이 문제에 함수를 사용할 때 항상 동일한 결과를 얻습니다.
입력 한 문자열은 회문이 아닙니다!
사용자가 입력 한 문자열이 회문이라도 동일한 출력을 얻습니다. 내 코드는 다음과 같습니다.
#include <stdio.h>
#include <string.h>
void reverse(char [],int);
int main() {
char a[100];int len, i = 0;
printf("Please enter the string to check: \n");
fgets(a,100,stdin);
//Loop to replace the '\n' inserted at the end of string due to fgets() with '\0'
for (int i = 0; i < strlen(a); ++i)
{
if (a[i] == '\n')
{
a[i] = '\0';
}
}
len = strlen(a);
reverse(a,len);
return 0;
}
void reverse(char b[100], int n) {
char c[100];int k=0;
//Read characters from b[] from the end and store them into c[]
for (int i = n-1; i >= 0; i--)
{
c[k] +=b[i];
k++;
}
c[k] = '\0';
//Check if the reversed string c[] and the actual string b[] are equal
if(strcmp(c,b) == 0)
printf("The Entered String Is Palindrome!\n");
else
printf("The Entered String Is Not Palindrome!\n");
}
reverse () 함수의 코드는 함수없이 동일한 문제를 해결하는 데 사용한 코드와 동일합니다 (그리고 해당 프로그램은 완벽하게 작동 함). 그러나 여전히 올바른 출력을 제공하지 않습니다. 내가 여기서 뭘 잘못하고 있니?
편집 : 좋아, 그래서 c[k] += b[i]
사용자 제안에 따라 제거했으며 이제 완벽하게 작동합니다. 하지만 여전히 이해가되지 않습니다. 내 말은 같은 프로그램에서 같은 줄을 사용했다는 의미인데, 유일한 차이점은 거기에서 함수 개념을 사용하지 않았고 완벽하게 잘 작동했다는 것입니다. 다음은 코드입니다.
#include <stdio.h>
#include <string.h>
int main() {
char a[100], b[100];
int k=0;
printf("Please enter the string: \n");
fgets(a,100,stdin);
//To replace the '\n' at the end of the string inserted by fgets()
for (int i = 0; i < strlen(a); ++i)
{
if(a[i] == '\n')
a[i] = '\0';
}
for (int i = strlen(a)-1; i >=0 ; i--)
{
b[k] += a[i];
k++;
}
if (strcmp(a,b) == 0)
{
printf("The entered string is palindrome!\n");
}
else
printf("The entered string is not palindrome! \n");
return 0;
}
내가 알지 못하는 개념이 있습니까? 그렇다면 저를 깨달으십시오.
자동 저장 기간이있는 초기화되지 않은 변수의 값을 사용하여 정의되지 않은 동작 을 호출했습니다 .
대신에 추가 c[k] +=b[i];
에서 불과 할당 값 b
으로 c[k] = b[i];
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다