CPS 205 Class 3 Chapter 3 Review of Chapter 2 homework ---------------------------- Formatted input and output -------------------------- printf is one of the most widely used functions in the C language. It is critically important skill to learn all that it can provide because it can make formatting text much easier in a variety of situations. Printf is made available in other languages, such as Perl, PHP, and C++, and its variants can be used to print to strings or to files. For now, we'll stick to printing to the screen. We'll cover the two basic functions for formatted input and output today. Formatted output ---------------- printf has two parts to its parameter list. The first is the format string. To go along with that format string are 0 or more variables, listed after the format. printf("Hello World"); Here the format sting has no variables following it, and that is because inside the format string are no formats. A format starts with a % (percent sign). Since there are no %'s in the string, this is a full and complete call to printf. Where printf really shines, though, is in its ability to change the way variables are displayed. To print a variable with printf, you first need to decide what variable to print. int i; printf("%d",i); Use %d to print an integer value. Here, in the format string, the only thing that prints is a formatted variable, signified by "%d". As seen in the previous examples and in the homework, though, you can easily mix and match regular strings and formatted strings: printf("The value of i is %d".i); The other major format we will be using is %f. This is used to print a floating point value. There are many other format types, which we will cover later. There are a few variations on %f that we should look at now, though. %e - prints a floating point value in scientific notation %g - prints a floating point value in decimal or scientific, whichever is shorter %lf - prints a double value (also %le and %lg) float f = 839.21; printf("%f",f); // 839.210 printf("%e",f); // 8.392e+02 printf("%g",f); // 839.21 The general scheme of a format is %-m.pX - = flags m = minimum width . = separates m and p p = precision X = the type specifier Only the % and the X are required. Flags ----- There are only a handful of flags, each of which has a specific role. Most common is the - flag, which is used to left justify numbers. Normally, numbers are right justified. The + flag is used to show a + sign if a number is positive. The space flag prefixes the number with a space if it is positive. The 0 flag 0-fills a right justified number. The minimum width field specifies the minimum number of spaces on the screen a number should take up. Normally printf only gives a number as much space as it needs - using the width allows you to easily create well-aligned columns of numbers. i = 123; printf("%d",i); // "123" printf("%5d",i); // " 123" two spaces on the left to print width of 5 printf("%05d",i); // "00123" zero-filled on the left printf("%-5d",i); // "123 " width of 5, left justified printf("%-05d",i); // "123 " the - overrides the 0 printf("%+d",i); // "+123" prints a + if positive printf("% d",i); // " 123" prints a space if positive printf("%+d",-i); // "-123" printf the - automatically i = 123456; printf("%4d",i); // "123456" width is just a minimum The precision flag is used mostly with floating point values, to specify how many decimal points to print, but it can be used with integer values for interesting effects. i = 123; printf("%6.4d",i); // " 0123" Width of 6, 4 significant digits Precision is more useful for floating point, though. The default will print three or six (typically) digits to the right of the decimal point. f = 3.14; printf("%f",f); // "3.140" or "3.140000" printf("%.4f",f); // "3.1400" printf("%.2f",f); // "3.14" This is often used for dollar amounts f = 5.679; printf("%.2f",f); // "5.68" Automatically rounds In this class, the formats you will be using the most are "%d", "%5d", "%05d", "%f", "%.0f", and "%.2f". To print a % in a string, use "%%". Escape sequences ---------------- Escape sequences are used to print values that you cannot type in. An escape sequence begins with the \ character. \a - bell or alert \b - backspace \f - form feed \n - newline \r - carriage return \t - tab \" - prints a " \\ - prints a backslash Formatted input --------------- scanf is a tricky and picky function, and many programmers learn very quickly that they need to replace it with something else. For our purposes, though, it will work just fine for now. scanf uses formats, just like printf, to tell it what kind of data to read in. int i; scanf("%d",&i); The "%d" tells scanf that it should read an int from the user. The "&i" is used to tell scanf where to place the data the user types in. The ampersand is required, at least for now. Leaving it off can, and most likely wiil, crash your program. Typically, in scanf, to avoid trouble, we place only one or a couple format specifiers. When using scanf, it can be critical that you tell the user how to type in the data, mixing a explanatory printf with the scanf. Once, a student thought that scanf and printf had to be used in pairs - this is not the case, and I want to be sure you know that. They often are, but a scanf need not be paired with a printf, nor vice versa. To combine format specifiers, just use more than one in the format: int i, j; scanf("%d%d",&i,&j); This might beg for a prompt like: printf("Type in two numbers, separated by spaces, then press ENTER: "); Note that in the format, the format specifiers have nothing between them. Scanf will read the first number, based on the first %d, and stop when it hits a space. Then it skips as many spaces as there are, and starts to read the second number. If there are no spaces, it can throw off scanf. 1 2 // reads the 1, sees the space, skips all spaces, reads the 2, sees // the "newline" and is done 9 4 // reads the 9, skips all spaces, reads the 4 8,9 // reads the 8, sees the comma and then skips all data until it gets // to the newline, then stops ... the second number is never filled in In this class, I won't complain about the fact that scanf can often break when you use it in your code, unless it is really bad. To force a specific set of data, use the characters in the format: scanf("%d-%d-%d",&i,&j,&k); Here, you would want a printf to be very specific: printf("Enter a social security number in xxx-xx-xxxx format: "); See section 3.2 on pages 36 through 39 for more info. Tips and Traps -------------- Don't use & in printf Always use & in scanf Be sure to use the % character Don't use %d when you should use %f (especially in scanf) Be sure to have as many variables in the list as in the format Don't do something like this: printf("Enter your phone number (use (xxx) xxx-1234): "); scanf("(%d) %d-%d",&area,&exc,&number); The format is too precise, and users are too imprecise. See the quiz for the better way.