源代码
#include <stdio.h> #include <stdlib.h> #define BUFFERSIZE 1024 int main() { unsigned int a,b,sum; char buffer[BUFFERSIZE]; printf("*************************************\n"); printf("* Welcome to use our counter *\n"); printf("* Input two intergers in one line *\n"); printf("* The sum will be printed *\n"); printf("* Input the char '#' to quit *\n"); printf("*************************************\n"); while ((fgets(buffer,BUFFERSIZE,stdin) != NULL) && (buffer[0] != '#')) { if(sscanf(buffer,"%d%d",&a,&b)!=2) { printf("The input is skipped:%s",buffer); continue; } sum = a + b; printf("The sum of %d and %d is %d\n",a,b,sum); } return 0; }
代码说明:
int fscanf (FILE *stream, char const *format, ...)
int scanf (char const *format, ...)
int sscanf (char const *string, char const *format, ...)
char *fgets (char *buffer, int BUFFER_SIZE, FILE *stream)
stdin为标准输入流
格式代码%后包括四种类型
1.星号(*):并不存储转换后的值,而是将其丢弃,用来跳过不需要的输入字符
2.宽度(一个非负整数):用来限制被读取转换的字符个数,在没有指定宽度的情况下,函数会连续读入字符知道遇到空白字符为止。
3.限定符
4.格式代码
d 十进制整型,有符号数
限定符h-short,l-long
u 十进制整型,无符号数
x 十六进制整型,无符号数
o 八进制整型,无符号数
限定符h-usigned short,l-unsigned long
f,e 一个浮点数
限定符l-double,L-long double
c 一个字符
s 一个字符串