方法一: 缺点:在编程规范里面,函数定义是实现单一功能,读取和反转是独立的功能
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 1000 void reverse(char line[]); int main() { int n = 0; int c; char line[MAX] = { 0 }; reverse(line); printf("%s", line); return 0; } void reverse(char s[]) { int n = 0; int i,c; char temp; while ((c =getchar()) != EOF ) { n++; s[n] = c; } for (i = 0; i <= n / 2; i++) { temp = s[i]; s[i] = s[n - i ]; s[n - i] = temp; } }方法二:
#include <stdio.h> #include <stdlib.h> #define MAX 1000 void reverse(char line[]); int main() { int c; int n = 0; char line[MAX] = {0}; while(1){ c = getchar(); if(c != EOF && c != '\n'){ line[n] = c; n++; continue; } if(c == EOF ){ break; } reverse(line); printf("%s\n",line); memset(line ,0 ,MAX); n = 0; } return 0; } void reverse(char s[]) { int i; int n = 0; char temp; for(n = 0;n < MAX; n++){ if(s[n] == 0){ break; } } n--; for(i = 0;i <= n/2; i++){ temp = s[i]; s[i] = s[n-i]; s[n-i] = temp; } return 0; }经检验 上述两种方法均可以实现功能,但是推荐第二种,更严谨