📄 c primer plus
字号:
第七章 C控制语句:分支和跳转
1、if .. else
// colddays.c -- finds percentage of days below freezing
#include <stdio.h>
#define SPACE ' ' // 空格
int main(void)
{
char ch;
ch = getchar(); // 读入一个字符
while (ch != '\n') // 当一行未结束时
{
if (ch == SPACE) // 如果是空格,直接打印字符
putchar(ch);
else // 否则,改变字符后再打印
putchar(ch + 1);
ch = getchar(); // 读取下一个字符
}
putchar(ch); // 打印换行字符
return 0;
}
/* cypher1.c -- alters input, preserving spaces */
#include <stdio.h>
#define SPACE ' ' // 空格
int main(void)
{
char ch;
while ( (ch=getchar()) != '\n') // !!! 读入一个字符,并判断是否为换行符
{
if (ch == SPACE) // 如果是空格,直接打印字符
putchar(ch);
else // 否则,改变字符后再打印
putchar(ch + 1);
}
putchar(ch); // 打印换行符
return 0;
}
// cypher2.c -- alters input, preserving non-letters
#include <stdio.h>
#include <ctype.h> // 为 isalpha() 提供原形
int main(void)
{
char ch;
while ((ch = getchar()) != '\n')
{
if (isalpha(ch)) // 如果是一个字母,
putchar(ch + 1); // 则改变它
else // 否则,
putchar(ch); // 原样打印它
}
putchar(ch); // 打印换行符
return 0;
}
2、条件运算符(?:)
x = (y<0) ? -y : y; // 取绝对值
相当于
if (y<0) x=-y; else x=y;
max = (a>b> ? a : b; // 比较大值
相当于
if (a>b) max=a; else max=b;
3、switch 多分支。switch比if else快些。
/* vowels.c -- uses multiple labels */
#include <stdio.h>
int main(void)
{
char ch;
int a_ct, e_ct, i_ct, o_ct, u_ct;
a_ct = e_ct = i_ct = o_ct = u_ct = 0;
printf("Enter some text; enter # to quit.\n");
while ((ch = getchar()) != '#')
{
switch (ch)
{
case 'a' :
case 'A' : a_ct++;
break;
case 'e' :
case 'E' : e_ct++;
break;
case 'i' :
case 'I' : i_ct++;
break;
case 'o' :
case 'O' : o_ct++;
break;
case 'u' :
case 'U' : u_ct++;
break;
default : break;
} /* end of switch */
} /* while loop end */
printf("number of vowels: A E I O U\n");
printf(" %4d %4d %4d %4d %4d\n",
a_ct, e_ct, i_ct, o_ct, u_ct);
return 0;
}
4、break、continue、goto 是跳转语句。
break 、 continue 用于循环中;
break 也用于 switch 中;
goto 用于任意位置,但尽可能不使用它!在深层循环中出现故障时用goto直接跳出,可以容忍。
例1:break
while(true)
{
ch=getchar();
if(ch=='\n')
break;
putchar(ch);
chcount++;
}
例2:continue
while((ch=getchar())!='\n')
{
if(ch=='')
continue;
putchar(ch);
chcount++;
}
例3:goto
top: ch = getchar();
.
.
.
if (ch!='y')
goto top;
5、ctype.h 定义了字符函数,同时支持ASCII、EBCDIC
isalnum() 字母或数字
isalpha() 字母
isblank() 一个标准的空白字符(空格、Tab、换行),或本地化定义的空白字符
iscntrl() 控制符,例如Ctrl + B
isdigit() 阿拉伯数字(0...9)
isgraph() 除空格符之外的所有可打印字符
islower() 小写字母
isprint() 可打印字符
ispunct() 标点符号(除空格和字母数字外的可打印字符)
isspace() 空白字符:空格、换行、走纸、回车、垂直制表符、水平制表符、或本地化定义的空白字符
isupper() 大写字母
isxdigit() 十六进制数字字符
tolower() 转换成小写字符
toupper() 转换成大写字符
if (ch >= 'a' && ch <= 'z') // 如果用 if (islower(ch)) 可工作于ASCII和EBCDIC字符编码,方便移值
printf("That's a lowercase character.\n");
// 统计字符、单词和行
// wordcnt.c -- counts characters, words, lines
#include <stdio.h>
#include <ctype.h> // for isspace()
#include <stdbool.h> // for bool, true, false
#define STOP '|'
int main(void)
{
char c; // read in character
char prev; // previous character read
long n_chars = 0L; // number of characters
int n_lines = 0; // number of lines
int n_words = 0; // number of words
int p_lines = 0; // number of partial lines
bool inword = false; // == true if c is in a word
printf("Enter text to be analyzed (| to terminate):\n");
prev = '\n'; // used to identify complete lines
while ((c = getchar()) != STOP)
{
n_chars++; // count characters
if (c == '\n')
n_lines++; // count lines
if (!isspace(c) && !inword)
{
inword = true; // starting a new word
n_words++; // count word
}
if (isspace(c) && inword)
inword = false; // reached end of word
prev = c; // save character value
}
if (prev != '\n')
p_lines = 1;
printf("characters = %ld, words = %d, lines = %d, ",
n_chars, n_words, n_lines);
printf("partial lines = %d\n", p_lines);
return 0;
}
6、stdbool.h 定义了bool替换_Bool,用true代替1,false代替0
7、iso646.h 改变拼写法,例如可用and代替&&,用or代替||,用not代替! (C99标准)
第八章 字符输入/输出和输入确认
1、输入缓冲区
/* echo.c -- repeats input */
#include <stdio.h>
int main(void)
{
char ch;
while ((ch = getchar()) != '#')
putchar(ch);
return 0;
}
输入输出结果:
abc[enter]
abc
DDDD#[enter]
DDDD
一般的操作系统下,输入的字符被保存在缓冲中,最终按下回车键时,
才传递给应用程序。一般输入缓冲有512或4096字节。
在 DOS/Windows 下,getche()非缓输冲输入,就是输入的字符马上显示。
在 UNIX 下,ioctl()来指定输入类型,此函数不是 ANSI C 标准函数。
在 ANSI C 中,setbuf()和setvbuf()可控制是否使用输入缓冲。
2、文件、流和键盘输入
文件读写、键盘输入、显示设备输出都作为流处理。
stdin 是键盘输入流;stdout 显示设备输出流。每个C程序自动要开stdin和stdout流。
getchar()、putchar()、printf()、scanf() 都是标准I/O函数,这些函数跟stdin和stdout流打交道。
3、文件结尾
文件结尾标志:第一种是Ctrl+Z作文件结束标志;第二种是根据文件大小判断。
新一点的DOS,UNIX都采用第二种方式。
getchar()、scanf()在到达文件结尾时返回EOF(End Of File),EOF一般定义为-1。
例如:while((ch=getchar()) != EOF)
/* echo_eof.c -- repeats input to end of file */
#include <stdio.h>
int main(void)
{
int ch;
while ((ch = getchar()) != EOF)
putchar(ch);
return 0;
}
输入输出结果:
abc[enter]
abc
[Ctrl+Z]
在UNIX系统下,按Ctrl+D表示文件结束;
在DOS/Windows下,按Ctrl+Z表示文件结束。
3、重定向
Unix、Linux和MS-DOS(2.0及以上版本),都有重定向功能。
下面是在操作系统下的执行的命令行:
输入重定向,即从in.txt读取字符,不是从键盘输入字符
echo_eof < in.txt
输出重定向,即将键盘输入字符写入out.txt中,不是输出到屏幕中
echo_eof > out.txt
组合重定向,从in.txt读入,写入out.txt
echo_eof < in.txt > out.txt
追加数据
echo_eof >> out.txt
管理输入输出,即将out程序的输出作为in程序的输入
out | in
4、读文本文件并显示内容
// file_eof.c --open a file and display it
#include <stdio.h>
#include <stdlib.h> // for exit()
int main()
{
int ch;
FILE * fp;
char fname[50]; // to hold the file name
printf("Enter the name of the file: ");
scanf("%s", fname);
fp = fopen(fname, "r"); // open file for reading
if (fp == NULL) // attempt failed
{
printf("Failed to open file. Bye\n");
exit(1); // quit program
}
// getc(fp) gets a character from the open file
while ((ch = getc(fp)) != EOF)
putchar(ch);
fclose(fp); // close the file
return 0;
}
5、getchar()接受任何指符,包括空格、制表符和换行符;
scanf()会跳过空格、制表符和换行,用%c跟getchar()效果一样。
/* showchar2.c -- prints characters in rows and columns */
#include <stdio.h>
void display(char cr, int lines, int width);
int main(void)
{
int ch; /* character to be printed */
int rows, cols; /* number of rows and columns */
printf("Enter a character and two integers:\n");
while ((ch = getchar()) != '\n')
{
if (scanf("%d %d",&rows, &cols) != 2) // 没有成功输入两个整数,则中止while
break;
display(ch, rows, cols);
while (getchar() != '\n') // 忽略上面scanf()输入时产生的换行符
continue;
printf("Enter another character and two integers;\n");
printf("Enter a newline to quit.\n");
}
printf("Bye.\n");
return 0;
}
void display(char cr, int lines, int width)
{
int row, col;
for (row = 1; row <= lines; row++)
{
for (col = 1; col <= width; col++)
putchar(cr);
putchar('\n'); /* end line and start a new one */
}
}
6、输入校验
/* checking.c -- 输入校验 */
#include <stdio.h>
//#include <stdbool.h>
// 确认输入了一个整数
int get_int(void);
// 确认范围的上下界限是否有效
bool bad_limits(int begin, int end, int low, int high);
// 计算从a到b之间的整数的平方和
double sum_squares(int a, int b);
int main(void)
{
const int MIN = -1000; // 范围的下界限制
const int MAX = +1000; // 范围的上界限制
int start; // 范围的下界
int stop; // 范围的上界
double answer;
printf("This program computes the sum of the squares of "
"integers in a range.\nThe lower bound should not "
"be less than -1000 and\nthe upper bound should not "
"be more than +1000.\nEnter the limits (enter 0 for "
"both limits to quit):\nlower limit: ");
start = get_int();
printf("upper limit: ");
stop = get_int();
while (start !=0 || stop != 0)
{
if (bad_limits(start, stop, MIN, MAX))
{
printf("Please try again.\n");
}
else
{
answer = sum_squares(start, stop);
printf("The sum of the squares of the integers ");
printf("from %d to %d is %g\n", start, stop, answer);
}
printf("Enter the limits (enter 0 for both "
"limits to quit):\n");
printf("lower limit: ");
start = get_int();
printf("upper limit: ");
stop = get_int();
}
printf("Done.\n");
return 0;
}
int get_int(void)
{
int input;
char ch;
while (scanf("%d", &input) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch); // 删除错误的输入
printf(" is not an integer.\nPlease enter an ");
printf("integer value, such as 25, -178, or 3: ");
}
return input;
}
double sum_squares(int a, int b)
{
double total = 0;
int i;
for (i = a; i <= b; i++)
total += i * i;
return total;
}
bool bad_limits(int begin, int end, int low, int high)
{
bool not_good = false;
if (begin > end)
{
printf("%d isn't smaller than %d.\n", begin, end);
not_good = true;
}
if (begin < low || end < low)
{
printf("Values must be %d or greater.\n", low);
not_good = true;
}
if (begin > high || end > high)
{
printf("Values must be %d or less.\n", high);
not_good = true;
}
return not_good;
}
7、菜单设计
/* menuette.c -- menu techniques */
#include <stdio.h>
// 用户选择
char get_choice(void);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -