C语言实战105例--1一个价值三天的BUG之限定符

本系列笔记是参考《C语言实战105例》及代码的学习笔记。

另外追加一个学习网址:C语言中文网:c语言程序设计门户网站(入门教程、编程软件)
http://c.biancheng.net/

还发现一个非常好的资源,是对c语言的基础解释。也是c语言中文网里面的子网页:编程基础http://c.biancheng.net/c/20/

本节是使用sscanf函数处理行定向的输入。程序为实现输入两个整数求和的功能。

注意:1、指针参数的类型必须是对应格式的代码的正确类型

           2、正确使用限定符(指定参数的长度)

代码如下:

#include<stdio.h>
#include<stdlib.h>
#define BUFFERSIZE 1024  /*允许处理的最长行有1024个字符*/
int main()
{
	int a,b,sum;         /*将输入的两个数分别存储在变量a和b中,sum=a+b*/
	char buffer[BUFFERSIZE];
	printf("***********************************\n");
	printf("*  Welcome to use our counter     *\n");
	printf("*  Input two integers in one line *\n");
	printf("*  The sum will be printed        *\n");
	printf("*  Input the char '#' to quit     *\n");
	printf("***********************************\n");
	/*从标准输入(stdin)读取输入的数据,存储在buffer中.
	如果读取的第一个字符是'#'则推出程序*/
	while((fgets(buffer,BUFFERSIZE,stdin)!=NULL)&&(buffer[0]!='#'))
	{
		if(sscanf(buffer,"%d %d",&a,&b)!=2)              /*处理存储在buffer中的一行数据*/
			{
				printf("The input is skipped:%s",buffer);/*如果输入的数字不是两个则报错*/
				continue;                               /*继续读取下一组数据*/			
			}
		sum=a+b;                                         /*计算a与b的和*/
		printf("The sum of %d and %d is %d\n",a,b,sum);  /*输出计算结果*/
	}
	return 0;
}

其中我不懂的地方:

  1. buffer--它一般用来定义数组,因为它本身的意思就是“缓冲区”,在C语言里,数组就是个缓冲区,所以用常常用它。
  2. 关于stdint.h--https://mp.csdn.net/postedit/82967645
  3. fgets函数----https://mp.csdn.net/postedit/82967810
  4. 本文的关键在于“限定符”--C语言类型限定符   http://c.biancheng.net/view/378.html

猜你喜欢

转载自blog.csdn.net/bellediao/article/details/82967285