【C语言学习】《C Primer Plus》第8章 字符输入/输出和输入确认

时间:2021-11-26 02:23:29

学习总结

1、缓冲区分为完全缓冲区(fully buffered)I/O和行缓冲区(line-buffered)I/O。对完全缓冲输入来说,当缓冲区满的时候会被清空(缓冲区内容发送至其目的地)。这类型的缓冲区通常出现在文件输入中。对于行缓冲I/O来说,遇到一个换行字符时将被清空缓冲区,键盘输入是标准的行缓冲区。

2、EOF是C对文件结尾的一个标识,在stdio.h头文件中定义,#define EOF (-1)。在使用键盘输入时,可以通过Ctrl+D模拟EOF信号:

#include <stdio.h>
int main(){
int ch;
while((ch=getchar())!=EOF){
putchar(ch);
}
return ;
}

Abc[Enter]

abc

123[Ctrl+D]123

3、>和<都是重定向运算符,必须是可执行程序加文件,拿以上程序为例子:

执行:./test > abc

输入:

abcdefg[Enter]1234567[Enter]

执行:cat abc

输出:

abcdefg

1234567

4、除了以上重定向运算符还有>>运算符,该运算符可使您的一个现有文件的末尾追加数据。还有管道运算符(|),其实这些运算符都是Unix和Linux上的运算符。

执行:./test >> abc

输入:

hijklmn[Enter]

执行:cat abc

输出:

abcdefg

1234567

hijklmn

执行:./test | grep aaa

输入:aaabbbccc[Enter]dddeeefff[Enter]ggghhhaaa[Enter]

输出:

aaabbbccc

ggghhhaaa

5、在创建与用户对话的程序时,需要考虑到所有的边界问题,例如程序只需要用户输入a、b、c、d的时候,万一用户输入量其他的且一大串的字符会如何处理等等情况。还有程序同时需要getchar进行字符输入和使用scanf进行数字输入,这两个函数中的每一个都能很好的完成其工作,但它们不能很好地混合在一起,这是因为getchar读取每个字符,包括空格、制表符和换行符,而scanf在读取数字时则会跳过空格、制表符和换行符。

6、编程题(题8)

 #include <stdio.h>

 int getChoice(void);
int getFirst(void); int main(){
int ch,t,y;
float a,b;
int c;
char sa[],sb[]; ch=getChoice();
if(ch==){
return ;
}else{
printf("Enter first number:");
scanf("%s",sa);
while(sscanf(sa,"%f",&a)!=){
printf("%s is not an number.\nPlease enter a number.such as 2.5, -1.78E8, or 3:",sa);
scanf("%s",sa);
}
printf("Enter second number:");
scanf("%s",sb);
while(sscanf(sb,"%f",&b)!=||(ch==&&b==)){
if(ch==&&b==){
printf("Enter a number other than 0:");
}else{
printf("%s is not an number.\nPlease enter a number.such as 2.5, -1.78E8, or 3:",sb);
}
scanf("%s",sb);
}
} if(ch==){
printf("%s+%s=%.1f\n",sa,sb,a+b);
}else if(ch==){
printf("%s-%s=%.1f\n",sa,sb,a-b);
}else if(ch==){
printf("%s*%s=%s\n",sa,sb,a*b);
}else{
printf("%s/%s=%.1f\n",sa,sb,a/b);
} return ;
} int getChoice(void){
int ch;
printf("Enter the operation of your choice:\n");
printf("a. add b. subtract\n");
printf("c. multiply d.divide\n");
printf("q. quit\n");
ch=getFirst();
while(ch!=&&ch!=&&ch!=&&ch!=&&ch!=){
printf("Please enter a right choice:\n");
ch=getFirst();
} } int getFirst(void){
int ch;
ch=getchar();
while(getchar()!=)
return ;
return ch;
}

运行结果:

Enter the operation of your choice:

a. add          b. subtract

c. multiply     d.divide

q. quit

f

Please enter a right choice:

d

Enter first number:qqq

qqq is not an number.

Please enter a number.such as 2.5, -1.78E8, or 3:1

Enter second number:0

Enter a number other than 0:1

1/1=1.0