1 / 38

Today

Today. Schedule Pong due Friday (April 11) Homework #9 due Friday (April 11) Homework #10 (on-line) Pointer Quizzes Student Evaluations Pong Questions?? I/O. 3.4 – I/O. Required : PM: Ch 11, pgs 205-243 Recommended : K&R, Chapter 7 Data Input and Output. “Gripe Sheet…”.

inge
Télécharger la présentation

Today

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Today • Schedule • Pong due Friday (April 11) • Homework #9 due Friday (April 11) • Homework #10 (on-line) • Pointer Quizzes • Student Evaluations • Pong • Questions?? • I/O 3.4 - Input and Output

  2. 3.4 – I/O Required: PM: Ch 11, pgs 205-243 Recommended: K&R, Chapter 7 Data Input and Output

  3. “Gripe Sheet…” • After every flight, Qantas pilots fill out a form, called a "gripe sheet", which tells mechanics about problems with the aircraft. The mechanics correct the problems, document their repairs on the form, and then pilots review the gripe sheets before the next flight. • Never let it be said that ground crews lack a sense of humor. Here are some actual maintenance complaints submitted by Qantas' pilots (marked with a P) and the solutions recorded (marked with an S) by maintenance engineers. • By the way, Qantas is the only major airline that has never, ever, had an accident. 3.4 - Input and Output

  4. “Gripe Sheet…” P: Left inside main tire almost needs replacement. S: Almost replaced left inside main tire. P: Test flight OK, except auto-land very rough. S: Auto-land not installed on this aircraft. P: Something loose in cockpit. S: Something tightened in cockpit. P: Dead bugs on windshield. S: Live bugs on back-order. P: Evidence of leak on right main landing gear. S: Evidence removed. 3.4 - Input and Output

  5. “Gripe Sheet…” P: DME volume unbelievably loud. S: DME volume set to more believable level. P: Friction locks cause throttle levers to stick. S: That's what friction locks are for. P: IFF inoperative in OFF mode. S: IFF always inoperative in OFF mode. P: Suspected crack in windshield. S: Suspect you're right. P: Number 3 engine missing. S: Engine found on right wing after brief search. 3.4 - Input and Output

  6. “Gripe Sheet…” P: Aircraft handles funny. S: Aircraft warned to straighten up, fly right, and be serious. P: Target radar hums. S: Reprogrammed target radar with lyrics. P: Mouse in cockpit. S: Cat installed. P: Noise coming from under instrument panel. Sounds like a midget pounding on something with a hammer. S: Took hammer away from midget. 3.4 - Input and Output

  7. Quiz 3.4.1 What makes one person’s code better/worse than another? Name 5 ways to improve your skills as a programmer 3.4 - Input and Output

  8. Quiz 3.4.1 (solution) What makes one person’s code better/worse than another? Bad or inconsistent formatting. Lots of copy and pasting Lacks proper documentation in the code More complicated than needed Doesn't improve over time Doesn't learn from mistakes Doesn't care about code quality • Easily maintained • Scaleable • Smaller footprint • Executes faster • Better resource usage 3.4 - Input and Output

  9. Quiz 3.4.1 (solution) Name 5 ways to improve your skills as a programmer • Analyze the problem clearly • Think twice about how to solve a problem • Gather complete requirements • Write a thorough implementation plan (or model) • Comment your code liberally • Use consistent naming conventions for variables • Organize your code • Test everything • Practice, practice, practice • Be prepared for change • Start simple and work towards complexity. Edited by Pildit, Imperatrix, Ben Rubenstein, Jack C and 52 others 3.4 - Input and Output

  10. CS 124 3.4 - Input and Output

  11. Learning Objectives… • Standard Libraries • Input/Output • Data Streams • printf() • scanf() • File I/O • fprintf and fscanf • sprintf and sscanf 3.4 - Input and Output

  12. Standard Libraries C Standard Library • Standard libraries promote cross-platform compatibility. • Useful for building complex programs. • Functions, types, and macros of the standard library are accessed by the #include directive. • Headers may be included in any order (and any number of times). • Actual I/O libraries can be linked statically or dynamically. 3.4 - Input and Output

  13. Standard Libraries ANSI Standard Libraries • <assert.h> Diagnostics • <ctype.h> Character Class Tests • <errno.h> Error Codes Reported by (Some) Library Functions • <float.h> Implementation-defined Floating-Point Limits • <limits.h> Implementation-defined Limits • <locale.h> Locale-specific Information • <math.h> Mathematical Functions • <setjmp.h> Non-local Jumps • <signal.h> Signals • <stdarg.h> Variable Argument Lists • <stddef.h> Definitions of General Use • <stdio.h> Input and Output • <stdlib.h> Utility functions • <string.h> String functions • <time.h> Time and Date functions 3.4 - Input and Output

  14. String Library <string.h> • Copy one string into another • char* strcpy (const char* dest, const char* src); • char* strncpy (const char* string1, const char* string2, size_t n) • Compare string1 and string2 to determine alphabetic order • intstrcmp (const char* string1,const char* string2); • intstrncmp (const char* string1, char* string2, size_t n); • Determine the length of a string • intstrlen (const char* string); • Append characters from string2 to string1 • char* strcat (const char* string1, const char* string2); • char* strncat(const char* string1, const char* string2, size_t n); • Find a string in a string • char* strstr (char* string1, const char* string2); 3.4 - Input and Output

  15. String Library <string.h> • memchr • memcmp • memcpy • memmove • memset • strchr • strcoll • strcspn • strerror • strpbrk • strrchr • strspn • strtok • strxfrm 3.4 - Input and Output

  16. Standard General Utilities Library <stdlib.h> • String conversion • atof Convert string to double • atoi Convert string to integer • atol Convert string to long integer • atoll Convert string to long longinteger • strtod Convert string to double • strtofConvert string to float • strtol Convert string to long integer • strtoldConvert string to long double • strtollConvert string to long longinteger • strtoul Convert string to unsigned long integer • strtoullConvert string to unsigned long longinteger 3.4 - Input and Output

  17. Standard General Utilities Library <stdlib.h> • Pseudo-random sequence generation • rand Generate random number • srand Initialize random number generator • Dynamic memory management • calloc Allocate and zero-initialize array • free Deallocatememory block • malloc Allocate memory block • realloc Reallocate memory block • Searching and sorting • bsearch Binary search in array • qsort Sort elements of array 3.4 - Input and Output

  18. Standard General Utilities Library <stdlib.h> • Integer arithmethics • abs Absolute value • div Integral division • labs Absolute value • ldiv Integral division • llabs Absolute value • lldivIntegral division • Types • div_t Structure returned by div (type ) • ldiv_t Structure returned by ldiv (type ) • lldiv_tStructure returned by lldiv (type ) • size_t Unsigned integral type (type ) 3.4 - Input and Output

  19. Quiz 3.4.2 • In which standard library would I find the following? • abs • malloc / free • memcpy / memset • printf / putchar • What is an I/O Stream? 3.4 - Input and Output

  20. Quiz 3.4.2 (solution) • In which standard library would I find the following? • abs • malloc / free • memcpy / memset • printf / putchar • What is an I/O Stream? <stdlib.h> <stdlib.h> <string.h> <stdio.h> An I/O Streamsare a flexible, efficient, and portable way of reading and writing data. A Stream is a file or a physical device (e.g. printer or monitor) which is manipulated with a pointer to the stream. 3.4 - Input and Output

  21. Data Streams I/O Data Streams • I/O is not directly supported by C but by a set of standard library functions defined by the ANSI C standard. • The stdio.h header file contains function declarations for I/O and preprocessor macros related to I/O. • stdio.h does not contain the source code for I/O library functions! • All C character based I/O is performed on streams. • All I/O streams must be opened and closed • A sequence of characters received from the keyboard is an example of a text stream • In standard C there are 3 streams automatically opened upon program execution: • stdin is the input stream • stdout is the output stream • stderr stream for error messages 3.4 - Input and Output

  22. printf() Formatted Output • The printf function outputs formatted values to the stdout stream using putc printf( const char *format, ... ); • The format string contains two object types: • Ordinary characters that are copied to the output stream • Conversion specifications which cause conversion and printing of the next argument in the argument list. printf("\nX = %d, Y = %d", x, y); Conversion specifications Characters 3.4 - Input and Output

  23. printf() Format Options • The format specifier uses the format: • %[flags][width][.precision][length]specifier • Formatting options are inserted between the % and the conversion character: • Field width "%4d" • Length modifier "%ld" • Left justified "%-4d" • Zero padded "%04d" • Sign "%+4d" • Variable field width"%*d" • Characters "\a","\b", "\n", "\r", "\t", "\v", "\xnn" • Specifiers: • Decimal%d or %i • String %s • Character %c • Hexadecimal %x • Unsigned decimal %u • Floating point %f • Scientific notation %e • Hex floating point%a • Pointer %p • % %% 3.4 - Input and Output

  24. printf() Formatted Output • A period separates the field width from the precision when formatting floating point numbers: printf("Speed = %10.2f", speed); • A variable field width is specified using an asterisk (*) formatting option along with a length argument (which must be an int): printf("%*s", max, s); • Left justification is specified by a minus character (-). The plus character (+) is replaced by the sign (either “+” or “-”). A space (' ') is replace by “-” if negative. printf("%-+04d", 10); 3.4 - Input and Output

  25. printf() Formatted Output Examples • Decimal %d or %i • String %s • Character %c • Hexadecimal %x • Unsigned decimal %u • Floating point %f • Scientific notation %e • Pointer %p • % %% int a = 100; int b = 65; char c = 'z'; char banner[ ] = "Hola!"; double pi = 3.14159; printf("The variable 'a' decimal: %d\n", a); printf("The variable 'a' hex: %x\n", a); printf("'a' plus 'b' as character: %c\n", a+b); printf("A char %c.\t A string %s\n A float %7.4f\n", c, banner, pi); 3.4 - Input and Output

  26. printf() Full Formatted Output Enable 3.4 - Input and Output

  27. scanf() Formatted Input • The function scanf is similar to printf, providing many of the same conversion facilities in the opposite direction: scanf( const char *format, ... ); • reads characters from the standard input (stdin), • interprets them according to the specification in format, • stores the results through the remaining arguments. • The format argument is a string; all other arguments must be a pointers indicating where the corresponding converted input should be stored. 3.4 - Input and Output

  28. scanf() scanf Conversion • For each data conversion, scanf will skip whitespace characters and then read ASCII characters until it encounters the first character that should NOT be included in the converted value. %d Reads until first non-digit. %x Reads until first non-digit (in hex). %s Reads until first whitespace character. • Literals in format string must match literals in theinput stream. • Data arguments must be pointers, because scanfstores the converted value to that memory address. 3.4 - Input and Output

  29. Doesn't match literal '/', so scanf quitsafter second conversion. scanf() scanf Return Value • The scanf function returns an integer, which indicates the number of successful conversions performed. • This lets the program check whether the input streamwas in the proper format. • Example:scanf("%s %d/%d/%d %lf", name, &bMonth, &bDay, &bYear, &gpa); Input StreamReturn ValueMudd 02/16/69 3.02 5 Muss 02 16 69 3.02 2 3.4 - Input and Output

  30. Quiz 3.4.3 #include <stdio.h> int main(void) { const char text[] = "Hello world"; inti; for ( i = 1; i < 12; ++i ) { printf("\"%*s\"\n", i, text); } } • What will the following do? • Output of the program to the right? 2. intn = 0; scanf("%d", n); 3. scanf("%d"); 4.printf("\nValue=%d"); 3.4 - Input and Output

  31. Quiz 3.4.3 (answers) #include <stdio.h> int main(void) { const char text[] = "Hello world"; inti; for ( i = 1; i < 12; ++i ) { printf("\"%*s\"\n", i, text); } } • What will the following do? • Output of the program to the right? 2. intn = 0; scanf("%d", n); 3. scanf("%d"); 4.printf("\nValue=%d"); • scanf will use the value of the argument as an address "H" "He" "Hel" "Hell" "Hello" "Hello " "Hello w" "Hello wo" "Hello wor" "Hello worl" "Hello world" • scanfwill get address from stack, where it expects to find first data argument. • %d will convert and print whatever is on the stack in the position where it expects to find the first argument. 3.4 - Input and Output

  32. File I/O I/O from Files • General-purpose I/O functions allow us to specify the stream on which they act • Must declare a pointer to a FILE struct for each physical file we want to manipulate FILE* infile; FILE* outfile; • The I/O stream is "opened" and the FILE struct instantiated by the fopen function • Arguments include the name of file to open and a description of the operation modes we want to perform on that file infile = fopen("myinfile", "r"); outfile = fopen("myoutfile", "w"); • Returns pointer to file descriptor or NULL if unsuccessful 3.4 - Input and Output

  33. File I/O I/O from Files • File operation modes are: • "r" for reading • "w" for writing (an existing file will lose its contents) • "a" for appending • "r+" for reading and writing • "b" for binary data • Once a file is opened, it can be read from or written to with functions such as • fgetc Read character from stream • fputc Write character to stream • fread Read block of data from stream • fwrite Write block of data to stream • fseek Reposition stream position indicator • fscanf Read formatted data from stream • fprintf Write formatted output to stream 3.4 - Input and Output

  34. File I/O I/O from Files #define LIMIT 1000 int main() { FILE* infile; FILE* outfile; double prices[LIMIT]; inti=0; infile = fopen("myinputfile", "r"); // open for reading outfile = fopen("myoutputfile", "w"); // open for writting if ((infile != NULL) && (outfile != NULL)) { while (i < LIMIT) { if ((fscanf(infile, "%lf", &prices[i]) == EOF)) break; printf("\nprice[%d] = %10.2lf", i, prices[i]); // ... process prices[i] i += 1; } } else printf("\nfopen unsuccessful!"); fclose(infile); fclose(outfile); } 3.4 - Input and Output

  35. Quiz 3.4.4 • Write an ASCII to integer function (ascii to integer). • Account for leading spaces and negative numbers. • Stop conversion at any non-digit. • Use a ternary operator somewhere in your implementation • Prototype: intmy_atoi(char* s); • Example printf("-345 = %d", my_atoi(" -345")); 3.4 - Input and Output

  36. Quiz 3.4.4 (solution) intmy_atoi(char* s) { intnegflg; intresult = 0; // handle leading spaces and minus sign while (*s == ' ') s++; if (negflg = (*s == '-')) s++; while ((*s >= '0') && (*s <= '9')) result = result * 10 + (*s++ - '0'); // return signed result return (negflg ? -result : result); } 3.4 - Input and Output

  37. sprintf / sscanf sprintf and sscanf • sprintf converts binary numbers to a string • int sprintf(char* buffer, const char* fmt,…); • buffer – char array big enough to hold converted number(s) • fmt – format specification • Variable list to be converted • Returns number of characters in converted string (not including null character • Useful in converting data to strings • sscanf converts a string to binary numbers • int sscanf(char* buffer, const char* fmt,…); • buffer – char array contains data to be converted • fmt – format specification • List of pointers to variables to hold converted values • Returns number of items converted • Useful to convert character data files 3.4 - Input and Output

  38. 3.4 - Input and Output

More Related