首页 > 代码库 > Tips for C

Tips for C

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%cunsigned char%ufloat%f
short%hdunsigned short%hudouble%lf
int%dunsigned int%ulong double%Lf
long%ldunsigned long%lu  
long long%lldunsigned 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.