关键字 :if,else,switch,continue,break,case,default,goto。
运算符 : && || ?:
函数 : getchar(),putchar(),ctype.h系列
getchar()
getchar()函数不带任何参数,它从输入队列中返回下一个字符。例如,下面的语句读取一下哥字符输入,病吧该字符的值赋给变量ch:
ch = getchar();
该语句与下面的语句效果相同:
scanf("%c",&ch);
putchar()
putchar()函数打印它的参数,例如,下面的语句吧之前赋值给ch的值作为字符打印出来:
putchar(ch);
该句等同于:
printf("%c",ch);
由于这些函数只处理字符,所以他们比更通用的scanf()和printf()函数更快,更简介,而且,getchar()和putchar()不需要转换说明,因为它们只处理字符。
eg:
#include<stdio.h>
int main(void){
char ch;
ch = getchar();
while(ch !='\n'){
if(ch == 0x20){
putchar(ch);
return 0;
}else{
putchar(ch+1);
ch = getchar();
}
}
putchar(ch);
return 0;
}
优先级
!运算符的优先级很高,比乘法运算符还高,与递增运算符的优先级相同,只比圆括号的优先级低。 && 运算符的优先级比 || 运算符高,但是两者的优先级都比关系运算符低,比赋值运算符高。
一个统计单词的程序
/**
* 统计字符数。单词数,行数
*/
#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
# define STOP '|'
int main(void){
char c; //读入字符
char prev; //读入的前一个字符
long n_chars = 0L; //字符数
int n_lines = 0; //行数
int n_words =0; // 单词数
int p_lines =0; //不完整的行数
bool inword = false;
printf("Enter text to be analyzed(| to terminate):\n");
prev="\n";
while((c = getchar()) != STOP){
n_chars++;
if(c == '\n'){
n_lines++;
}
if(!isspace(c)&&!inword){
inword = true;
n_words++;
}
if(isspace(c)&&inword){
inword = false;
prev = c;
}
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;
}
}
辅助循环的 break continue
在while 的循环内:
continue 的时候,会忽略 continue 后面的语句,到 while 入口继续执行
break 的时候,会直接跳出 while 的循环,停止 while 循环
![](https://img.haomeiwen.com/i5531021/06ff191724a7ed8c.png)
/**
* continue 和 break 和 多重选择:switch 和break
*/
#include<stdio.h>
#include<ctype.h>
int main(void){
char ch;
printf("Give me a letter of the alphabet ,and I will Give\n");
printf("an animal name \nbeginning with that letter.\n");
printf("Please type in a letter; type # to end my act.\n");
while((ch = getchar())!='#'){
if ('\n' == ch)
{
continue;
}
if(islower(ch))
switch(ch)
{
case 'a':
printf("argali,a wildd sheep of Asia \n");
break;
case 'b':
printf("babirusa ,a wild pig of Malay\n");
break;
case 'c':
printf("coati,racoonlike mammal\n");
break;
default:
printf("aaaaaaaaabbbbbbbbbbbcccccccc");
}
else
printf("I recognize only lowercase letter.\n");
while(getchar()!= '\n')
continue;
printf("Please type another letter or a #.\n");
}
printf("Bye \n");
return 0;
}
goto语句
早期版本的BASIC和FORTRAN所依赖的goto语句, 在 C 中 仍然可用。 但是C和其他两种语言不同,没有goto语句C程序也能运行良好。
在C中应尽量避免使用goto语句。
isspace() 和 isalpha()
isspace()是判断是否为空格
isalhpa()是判断是否为英文字母
文中小结
- 测试条件通常都是关系表达式,即用一个关系运算符(如 < 或 ==)的表达式,使用C的逻辑运算符,可以吧关系表达式组合成更复杂的测试条件。
- 在多数情况下,用条件运算符(?:)写成的表达式比 if else 语句更简洁。
- ctype.h系列的字符函数(如:issapce()和 isalpha())为创建以分类为基础的测试表达式,提供了便捷的工具。
- switch 语句可以在一系列以整数作为标签的语句进行选择,如果紧跟在switch关键字后的测试条件的整数值与某标签匹配,程序就转至执行匹配的标签语句。然后在遇到break之前,继续执行标签语句后面的语句。
- break,continue和goto语句都是跳转语句,使程序流跳转至程序的另一边。break 是跳转出去。continue会跳出接下来的语句,转而while继续循环。
网友评论