刷题《C programming language》Exercise 5-6

#include <stdio.h>
2 #include <string.h>
3
4 void reverse(char *str) {
5 if (!str) {
6 return;
7 }
8
9 char *start = str;
10 char *end = str + strlen(str) - 1;
11 while (start < end) {
12 char temp = *start;
13 *start++ = *end;
14 *end-- = temp;
15 }
16 }
17
18 int main()
19 {
20 char * str_org = NULL ;
21 size_t n = 0;
22 while( getline(&str_org, &n, stdin ) != -1 )
23 {
24 printf( "%s\n", str_org );
25 reverse( str_org );
26 printf( "%s\n", str_org );
27 }
28 }
1.注意getline函数的调用 ssize_t getline(char **lineptr, size_t *n, FILE *stream); 及返回值-1的判断条件。
2.经典的字符串逆序算法。
#include <stdio.h>
int atoi(const char *str) {
int result = 0;
while (*str >= '0' && *str <= '9') {
result = result * 10 + (*str - '0');
str++;
}
return result;
}
void itoa(int n, char *str) {
if (n < 0) {
*str++ = '-';
n = -n;
}
char *ptr = str;
while (n > 0) {
*ptr++ = '0' + (n % 10);
n /= 10;
}
*ptr-- = '\0';
// Reverse the string
char *start = str;
while (start < ptr) {
char temp = *start;
*start++ = *ptr;
*ptr-- = temp;
}
}
int main()
{
char number1[] = "12345";
printf("atoi=%d\n", atoi(number1));
char number2[100];
itoa(123456,number2);
printf("itoi=%s\n",number2);
return 0;
}
1.atoi 和 itoa是integer 和ASCALL字符之间的转换函数
2.数字字符串和数字相互转换的经典算法
//#include <stdio.h>
//#define MAXLINE 1000 /* maximum input line length */
//
//int my_getline(char *line, int maxline);
//
//int main() {
// char line[MAXLINE];
// while (my_getline(line, MAXLINE) > 0) {
// printf("%s", line);
// }
// return 0;
//}
//
///* my_getline: read a line into s, return length */
//int my_getline(char *s, int lim) {
// int c;
// char *start = s;
//
// while (--lim > 0 && (c = getchar()) != EOF && c != '\n') {
// *s++ = c;
// }
// if (c == '\n') {
// *s++ = c;
// }
// *s = '\0';
// return s - start;
//}
#include <stdio.h>
#include <stdlib.h>
/* 如果你的编译器支持 _GNU_SOURCE 宏,则 getline 函数会被定义 */
#ifdef _GNU_SOURCE
#undef getline
#endif
int my_getline(char **lineptr, size_t *n, FILE *stream);
int main() {
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = my_getline(&line, &len, stdin)) != -1) {
printf("%s", line);
}
free(line);
return 0;
}
/* my_getline: read a line into *lineptr, return length */
int my_getline(char **lineptr, size_t *n, FILE *stream) {
char *line = *lineptr;
ssize_t count = getline(&line, n, stream);
*lineptr = line;
return count;
}
本文介绍了在C语言中实现字符串逆序、整数到ASCII字符转换(atoi)和ASCII字符到整数转换(itoa)的方法,以及使用getline函数处理输入流的经典示例。
896

被折叠的 条评论
为什么被折叠?



