Tác giả Matt Mahoney, mmahoney@cs.fit.edu.
Đội ngũ giảng viên TechMaster biên soạn, định dạng lại cho dễ đọc hơn.
C++ cheat sheet – phần 1
C/C++ STANDARD LIBRARY
Only the most commonly used functions are listed. Header files without .h are in namespace std. File names are actually lower case.
STDIO.H, CSTDIO (Input/output)
FILE* f=fopen("filename", "r"); // Open for reading, NULL (0) if error
// Mode may also be "w" (write) "a" append, "a+" update, "rb" binary
fclose(f); // Close file f
fprintf(f, "x=%d", 3); // Print "x=3" Other conversions:
"%5d %u %-8ld" // int width 5, unsigned int, long left just.
"%o %x %X %lx" // octal, hex, HEX, long hex
"%f %5.1f" // float or double: 123.000000, 123.0
"%e %g" // 1.23e2, use either f or g
"%c %s" // char, char*
"%%" // %
sprintf(s, "x=%d", 3); // Print to array of char s
printf("x=%d", 3); // Print to stdout (screen unless redirected)
fprintf(stderr, ... // Print to standard error (not redirected)
getc(f); // Read one char (as an int) or EOF from f
ungetc(c, f); // Put back one c to f
getchar(); // getc(stdin);
putc(c, f) // fprintf(f, "%c", c);
putchar(c); // putc(c, stdout);
fgets(s, n, f); // Read line into char s[n] from f. NULL if EOF
gets(s) // fgets(s, INT_MAX, f); no bounds check
fread(s, n, 1, f); // Read n bytes from f to s, return number read
fwrite(s, n, 1, f); // Write n bytes of s to f, return number written
fflush(f); // Force buffered writes to f
fseek(f, n, SEEK_SET); // Position binary file f at n
ftell(f); // Position in f, -1L if error
rewind(f); // fseek(f, 0L, SEEK_SET); clearerr(f);
feof(f); // Is f at end of file?
ferror(f); // Error in f?
perror(s); // Print char* s and error message
clearerr(f); // Clear error code for f
remove("filename"); // Delete file, return 0 if OK
rename("old", "new"); // Rename file, return 0 if OK
f = tmpfile(); // Create temporary file in mode "wb+"
tmpnam(s); // Put a unique file name in char s[L_tmpnam]
STDLIB.H, CSTDLIB (Misc. functions)
atof(s); atol(s); atoi(s);// Convert char* s to float, long, int
rand(), srand(seed); // Random int 0 to RAND_MAX, reset rand()
void* p = malloc(n); // Allocate n bytes. Obsolete: use new
free(p); // Free memory. Obsolete: use delete
exit(n); // Kill program, return status n
system(s); // Execute OS command s (system dependent)
getenv("PATH"); // Environment variable or 0 (system dependent)
abs(n); labs(ln); // Absolute value as int, long
STRING.H, CSTRING (Character array handling functions)
Strings are type char[] with a ‘
Bình luận