使用教材
《“笨办法” 学C语言(Learn C The Hard Way)》
https://www.jianshu.com/p/b0631208a794
ex14.c
- 打印属于字母或者空格的字符及其对应的ASCII值
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// forward declaration
void print_letters(char arg[], int len);
void print_arguments(int argc, char *argv[])
{
int i = 0 ;
int len = 0;
for(i = 0; i < argc; i++) {
len = strlen(argv[i]);
print_letters(argv[i], len);
}
}
void print_letters(char arg[], int len)
{
int i = 0 ;
for(i = 0 ; i< len; i++) {
char ch = arg[i];
if(isalpha(ch) || isblank(ch)) {
printf("'%c' == %d \n", ch, ch);
}
}
printf("\n");
}
int main(int argc, char *agrv[])
{
print_arguments(argc, agrv);
return 0;
}
Makefile
CC=clang
CFLAGS=-Wall -g
clean:
rm -f ex14
run
anno@anno-m:~/Documents/mycode/ex14$ make ex14
clang -Wall -g ex14.c -o ex14
anno@anno-m:~/Documents/mycode/ex14$ ./ex14
'e' == 101
'x' == 120
anno@anno-m:~/Documents/mycode/ex14$ ./ex14 "I go 3 space"
'e' == 101
'x' == 120
'I' == 73
' ' == 32
'g' == 103
'o' == 111
' ' == 32
' ' == 32
's' == 115
'p' == 112
'a' == 97
'c' == 99
'e' == 101
anno@anno-m:~/Documents/mycode/ex14$ ./ex14 hell1o worl2d !3
./ex14 hell1o worl2d ls
'e' == 101
'x' == 120
'h' == 104
'e' == 101
'l' == 108
'l' == 108
'o' == 111
'w' == 119
'o' == 111
'r' == 114
'l' == 108
'd' == 100
'l' == 108
's' == 115
note
-
前置声明 forward declaration:解决未定义函数之前就可以使用这个函数;
-
isalpha(ch)
、isblank(ch)
来自头文件<ctype.h>
SYNOPSIS
#include <ctype.h>
int isalnum(int c);
int isalpha(int c);
int isascii(int c);
int isblank(int c);
int iscntrl(int c);
int isdigit(int c);
int isgraph(int c);
int islower(int c);
int isprint(int c);
int ispunct(int c);
int isspace(int c);
int isupper(int c);
int isxdigit(int c);
-
strlen
来自<string.h>
:返回字符串长度,不包括最后的\0
NAME
strlen - calculate the length of a string
SYNOPSIS
#include <string.h>
size_t strlen(const char *s);
DESCRIPTION
The strlen() function calculates the length of the string s, excluding
the terminating null byte ('\0').
RETURN VALUE
The strlen() function returns the number of bytes in the string s.
- Indentation style
网友评论