练习1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序。
#include <stdio.h>
#define MAXLINE 1000
int getline(char s[], int lim);
void reverse(char s[]);
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
int len;
char line[MAXLINE];
while ((len = getline(line, MAXLINE)) > 0) {
reverse(line);
printf("[%d]%s", len, line);
}
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++) {
s[i] = c;
}
if (c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
void reverse(char s[])
{
int i = 0, j = 0;
char temp;
while(s[i] != '\0') {
i++;
}
i--;
if (s[i] == '\n') {
i--;
}
while (j < i) {
temp = s[j];
s[j] = s[i];
s[i] = temp;
j++;
i--;
}
}
运行结果:
标签:练习题,reverse,19,void,++,char,int,程序设计,line From: https://blog.csdn.net/VincentKCSDN/article/details/141759293