====================================== Notes for Lecture 5 - January 29, 2008 ====================================== * General discussion of how to learn a second language ** Read sample code ** Read textbook quickly to get overview ** Ask questions * Type char ** sizeof(char) == 1 ** can be signed or unsigned ** character constants e.g. 'a' have type int ** char is a numeric type; can do arithmetic on them Example: The ASCII character code for 'a' is 96. putchar(96) prints the letter 'a'; so does putchar('a'). putchar(97) prints the letter 'b'; so does putchar('a'+1). * Defining pi (needed in PS2) ** #define PI 3.14159 This substitutes the numeric literal for each occurrence of PI. Accurate only to number of digits specified. ** const double pi = 2*acos(0.0); This computes pi using the math library function acos() and uses the result to initialize a read-only variable "pi". ** const Means value can't be changed after initialization. Otherwise just like a variable. * Overview of scanf() and sscanf() ** Character buffer is array of characters *** Example: char buf[100]; ** Using scanf() format to read line *** Format "%99[^\n]" *** ret = scanf( "%99[^\n]", buf ); Reads to end of line or until 99 characters have been read. Appends null character '\0' to buffer. Returns 1 if 1 or more characters found. Returns 0 if line is empty. Returns EOF on end of file or read error. *** & not needed in front of buf Array names are already considered to be pointers. ** sscanf() *** Like scanf(), but reads from a string *** Example: ret = sscanf( buf, "%i", &x ) Reads a decimal integer from buf, converts it to an int, and stores it in x. Returns 1 if successful. Returns 0 if a non-integer was encountered. Returns EOF if end of buffer reached. * blocks and scoping ** block can be used where a statement is permitted ** blocks can contain declarations and executable statements ** names declared in a block are not visible outside of the block * Statements ** if ** do ... while ** while ** switch ** break ** continue ** goto Rarely needed. Don't use in this course without permission.