COSC450: A Introductory Comparison of C and C++.
See Appendix B of the COSC220 text: Date Abtraction & Structures Using C++
for a comparison of C and C++.
This document brushes the surface of C operations, but it's enough to get you
going! Recommended: A good C reference. THE C PROGRAMMING
LANGUAGE by Kernighan and Ritchie, Prentice Hall is a great reference. It is
out in paperback.
We'll focus on:
1. Formatted I/O
2. File processing
3. Parameter passing
4. Structs
5. A look at some C libraries
1. Formatted Input/Output
scanf and printf require the stdio.h library.
scanf
Reads from keyboard, ignoring blank space.
Except for strings, actual params must be preceded by '&'.
That is, args must be pointers!
Must specify argument types, in order, in a string using '%'.
%d decimal integer
%i integer (may be octal (leading 0) or hex (leading 0x)).
%u unsigned integer
%c character
%s string Puts '\0' at end for you.
%e,%f,%g Optional sign; opt decimal point; optional exponent.
Numerics can be preceded by 'h' to indicate short, 'l' to indicate long, as in
%li for long integer
d,i,u, etc are called "conversion chars".
Examples:
To read in 25 Feb 1999 with declarations
int day, year; char monthName[20];
...
scanf("%i %s %i", &day,monthName,&year);
To read in 02/25/99 with month as type int:
...
scanf("%i/%i/%i", &month,&day,&year);
printf
The output function printf translates data values into strings of characters
to be displayed at the screen.
If only a literal string is to be displayed, no conversion characters are
needed.
Each conversion specification begins with a '%' and ends with a
conversion character, just as scanf does.
Between the '%' and the conversion character there may be, in this order:
. A minus sign to specify left justification
. A number to specify field width
. A period to separate field width from precision
. A number for precision to specify:
Max # of charas to be printed from a string OR
Number of digits after a decimal point OR
A floating point value OR
The minimum # of digits for an integer.
conversion char argument type
d,i int decimal, base 10 (as opposed to octal or hex)
u int unsigned integer
c int single character
s ptr to char string
f double double floating point
e,E double double floating point
Ex: -5.43234e+3
g,G double double floating point in exponent notation
Trailing zeroes or decimal points not printed.
Use %e or %E if exponent < -4 or >= the precision; otherwise use %f.
% '%' Prints the '%'. No assignment made.
See printf.c and tstio.c
2. File processing
See TstFiles.c.
stdio.h must be included.
A file variables is a pointer to the type FILE, as in FILE* inputFile;
To OPEN a file:
inputfile = fopen("filName", "r");
"r" open for reading
"w" open for writing (discards previous contents)
"a" open for appending (creates new if doesn't exist already)
To CLOSE a file:
fclose(inputFile);
If the file name (logical, not physical) is NULL at any time, that means that you are at the end of the file, as in--
inputFile = fopen("filName","r");
if (inputFile == NULL)
... /* print error message*/
To read from a file, use fscanf:
Use the same formatting as for reading from the keyboard (standard input) but use the filename as the first parameter to fscanf, as in--
fscanf(inputFile,"%s %d", name, &age);
You can use fscanf as a function, returning an integer which can be tested for the end-of-file constant (as defined in stdio.h, typically -1), as in--
status = fscanf(inputFile,"%s %d", name, &age);
while (status != EOF)
... /* continue processing the file */
To write to a file, use fprintf:
Use the same formatting as for printing to the screen (standard output) but use the filename as the first parameter to fprintf, as in--
fprintf(outputFile,"%15s%6d\n", name, age);
You can also use stdout and stdin as logical file names for the screen (standard output) and the keyboard (standard input), as in --
fgetc(stdin) to get the next character read from the keyboard.
3. Parameter passing
Pass-by-value:
Same as in C++.
Pass-by-reference:
Nothing required for strings of characters (as in C++).
For all other data:
A. Pass in the address of the value:
Ex of a call: Swap (&num1,&num2);
B. The formal parameter is expressed as a pointer:
Ex:
void Swap (int* num1, int* num2);
C. Every reference to the pass-by-reference parameter inside the procedure must use pointers:
Ex:
void Swap (int* num1, int* num2)
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
See TestSubs.c demo, which shows the syntax for passing a pass-by-reference parameter in a subroutine to another subroutine as pass-by-reference.
4. Structs
See TstStruc.c demo.
The only difference betwen C and C++ here is that once you've defined a struct
data type, when you declare a variable to be of that struct data type you must
still use the word "struct" at the beginning of the declaration. C++ does not
require that you do that.
Ex: typedef struct someStruct
{
...
};
struct someStruct s1,s2;
struct someStruct ListOfStructs[10];
5. A look at some C libraries
Use the Borland C++ help facility to find out more about some of the C functions
listed here.
Library Purpose Exs of functions and procedures
stdio.h I/O functions fopen, fclose, rename, printf, scanf, fprintf, fscanf, sscanf, fflush, remove, sprintf, vprintf,
fgetc, fgets, fputc, fputs, getc, getchar, gets,
purc, putchar, puts, ungetc, fseek, ftell, rewind,
fgetpos, fsetpos, clearerr, feof, ferror, perror, ...
ctype.h Testing chars (Similar to C++)
isalnum, isalpha, iscntrl, isdigit, isgraph,
islower, isprint, ispunct, isspace, isupper,
isxdigit, toupper, tolower, ...
string.h For strings (Same or very close to C++)
strcpy, strncpy, strcat, strncat, strcmp, strncmp,
strchr, strrchar, strspn, strcspn, strpbrk, strstr,
strlen, strerror, strtok, ...
math.h Math functions (Same or very close to C++)
Sin, cos, tan, asin, acos, atan, atan2, sinh,
cosh, tanh, exp, log, log10, pow, sqrt, ceil,
floor, fabs, ldexp, frexp, modf, fmod, ...
stdlib.h Utility functions atof, atoi, atol, strtod, strtol, strtoul, rand,
srand, calloc, malloc, realloc, free, abort, exit
atexit, system, getenv, bsearch, qsort, abs,
labs, div, ldiv, ...
time.h Day, time functions tm_sec, tm_min, tm_hour, tm_mday,
tm_mon, tm_year, tm_wday, tm_yday,
tm_isdst, clock, time, difftime, mktime,
asctime, ctime, gmtime, localtime,
strftime, ...
limits.h, float.h
Max,min for integer and floating point types.
assert.h Allows use of assertions.
signal.h Handle interrupts
And others...