码迷,mamicode.com
首页 > 其他好文 > 详细

Tips for C

时间:2014-06-18 10:14:22      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   color   

1. sizeof(literal-string) is number of bytes plus 1 (NULL is included), while strlen(literal-string) is number of bytes.

2. Printf and scanf format

Before use PRIXxx or SCNXxx, add following code before any code.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdint.h>

Many macros for input/output are defined inttypes.h, you need not to remember, just consult C language manual

For Standard C, it‘s very useful to remember following printf/scanf formats 

char %c unsigned char %u float %f
short %hd unsigned short %hu double %lf
int %d unsigned int %u long double %Lf
long %ld unsigned long %lu    
long long %lld unsigned long long %llu    

 

 

 

 

 

3. A printf Pitfall: a lesson from poj 3299

Wrong Answer: printf("T %0.1lf D %0.1lf H %0.1lf\n", T, D, H);

Accepted: cout << "T " << setprecision(1) << fixed << T << " D " << D << " H " << H << endl;

Float-point rounding rule is a little bit complex and confusion.

 4. scanf VS. fgets

1) To get a line, fgets is recommanded; to get a word without, use scanf

if(fget(buf, bufsize, stdin) == NULL)
    perror("EOF or I/O error");
if(scanf("%s", buf) == EOF)
    perror("EOF");

Following code blocks are not equal, even when lines inputted do not contain any blanks.

fgets(line, linesize, stdin);
scanf("%s", line);
while(getchar() != \n);

In the case of online judge system, to get lines from standard input, fgets is always preferred.

Tips for C,布布扣,bubuko.com

Tips for C

标签:style   class   blog   code   http   color   

原文地址:http://www.cnblogs.com/freedom-is-power/p/3755983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!