-
C언어 문자열 거꾸로 바꾸기 (Inverts the string)C language 2017. 8. 17. 22:12SMALL
j = n-1; 이부분을 보면 -1 을 하지 않을 경우 temp[0]에 '\0' 종료 문자가 들어가므로 , 아무것도 출력하지 않는다.
without -1, temp[0] gets '\0' and nothing is output.
#include <stdio.h> #include <string.h> // strlen() 사용을 위해 (for use strlen) void reverse (char *, unsigned long); char *sgets (char *, int n); int main(void) { char ar[50]; unsigned long n; puts("Enter any sentence : (to exit just push enter)"); while (sgets(ar,50) != NULL && ar[0] != '\0') { n = strlen(ar); reverse(ar,n); puts("Enter any sentence : (to exit just push enter)"); } puts("Bye!"); } void reverse (char *ar, unsigned long n) { int i,j; char temp[n]; j = n-1; for (i = 0; i < n; i++,j--) temp[i] = ar[j]; printf("%s\n",temp); return; } char *sgets (char *ar, int n) { fgets(ar, n, stdin); int i = 0; while(ar[i] != '\n' && ar[i] != '\0') i++; if (ar[i] == '\n') ar[i] = '\0'; else while (getchar() != '\0') continue; return ar; }
아래와 같이 입력한 문자열을 거꾸로 바꿔주는것을 볼수있다.
As you can see, The string is inverted.
그리고 엔터만 입력하게 되면 프로그램은 종료된다.
and then The program exits when entering only enter
BIG'C language' 카테고리의 다른 글
ctype.h 을 활용한 예제(Example using ctype.h) (0) 2017.08.19 C언어 문자열내 빈칸(스페이스) 지우기(remove space in string) (0) 2017.08.18 문자열내에서 문자찾기 (0) 2017.08.11 main()함수에 전달인자 넣기(Passing arguments to main () function) (0) 2017.08.09 strchr 사용법 (strchr usage) (0) 2017.08.08