Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Show how to modify the addfrac.c program of section 3.2 so that the user is allowed to enter fractions that contain spaces before and after

Show how to modify the addfrac.c program of section 3.2 so that the user is allowed to enter fractions that contain spaces before and after each / character.
I put pages os section 3.2 image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
3.2 The scanf Function Just as print f prints output in a specified format. scanf reads input according to a particular format. A scanf format string, like a printf format string, may contain both ordinary characters and conversion specifications. The conversions allowed with scanf are essentially the same as those used with print:f In many cases, scanf format string will contain only conversion specifica- tions, as in the following example: int i, j float x, y Suppose that the user enters the following input line 1 -20 .3-4.0e3 scanf will read the line, converting its characters to the numbers they represent. and then assign I. -20, 0.3. and -4000.0 to i, j. x. and y. respectively. "Tightly packed" format strings like "%d%d%f%f" are common in scanf calls, printf format strings are less likely to have adjacent conversion specifications. scanf, like printf, contains several traps for the unwary. When using scanf, the programmer must check that the number of conversion specifications matches the number of input variables and that each conversion is appropriate for the corresponding variable-as with printf, the compiler isn't required to check s cant will-reaartneTI ne, converti ngTscmaracters- memumoers mey represem and then assign 1, -20, 0.3. and -4000.0 to i, j. x. and y. respectively. Tightly packed" format strings like "%d%d%f%f" are common in scanf calls printf format strings are less likely to have adjacent conversion specifications. scanf. like printf, contains several traps for the unwary. When using scanf, the programmer must check that the number of conversion specifications matches the number of input variables and that each conversion is appropriate for the corresponding variable-as with printf, the compiler isn't required to check for a possible mismatch. Another trap involves the & symbol, which normally pre- cedes cach variable in a scanf call. The & is usually (but not always) required. and it's the programmer's responsibility to remember to use it. Forgetting to put the & symbol in front of a variable in a call of scanf will have unpredictable-and possibly disastrous-results. A program crash is a common outcome. At the very least, the value that is read from the input won't be stored in the variable; instead, the variable will retain its old value (which may be meaning- less if the variable wasn't given an initial value). Omitting the & is an extremely common error-be careful! Some compilers can spot this error and produce a warning message such as "format argument is not a pointer" (The term pointer is defined in Chapter I; the & symbol is used to create a pointer to a variable.) If you get a warning, check for a missing & 3.2 The scanf Function 43 Calling scanf is a powerful but unforgiving way to read data. Many profes- sional C programmers avoid scanf, instead reading all data in character form and converting it to numeric form later. We'll use scanf quite a bit, especially in the early chapters of this book, because it provides a simple way to read numbers. Be aware, however, that many of our programs won't behave properly if the user enters unexpected input. As we'll see later, it's possible to have a program test whether scanf successfully read the requested data (and allempt to recover if it didn't). Such tests are impractical for the programs in this book-they would add detecting errors in scant 223 too many statements and obscure the point of the examples. How scanf Works scanf can actually do much more than I've indicated so far. It is essentially a "pattern-matching" function that tries to match up groups of input characters with conversion specifications. Like the printf function, scanf is controlled by the format string. When it is called, scanf begins processing the information in the string, starting at the left. For each conversion specification in the format string, scanf tries to locate an item of the appropriate type in the input data. skipping blank space if necessary scanf then reads the item, stopping when it encounters a character that can't pos- sibly belong to the item. If the item was read successfully, scanf continues pro- cessing the rest of the format string. If any item is not read successfully, scanf returns immediately without looking at the rest of the format string (or the remain- ing input data). As it searches for the beginning of a number, scanf ignores white-space characters (the space, horizontal and vertical tab, form-feed. and new-line charac- ters). As a result, numbers can be put on a single line or spread out over several lines. Consider the following call of scanf: scanf("%d2d% f % f " , &, &j, &x , &y); Suppose that the user enters three lines of input: 1 -20 3 -4.0e3 scanf sees one continuous stream of characters: 10-20..30-4.0e3 (I'm using to represent the space character and to represent the new-line char- acter.) Since it skips over white-space characters as it looks for the beginning of each number, scanf will be able to read the numbers successfully. In the follow ing diagram, an s under a character indicates that it was skipped. and an r indi- cates it was read as part of an input item 10-20...30-4.0e30 ssrsrrrsssrrssssrrrrrr 44 Chapter 3 Formatted Input/Output scanf "peeks" at the final new-line character without actually reading it. This new-line will be the first character read by the next call of scanf. What rules does scanf follow to recognize an integer or a floating-point number? When aked to read an integer. scanf first searches for a digit, a plus sign, or a minus sign; it then reads digits until it reaches a nondigit. When asked to read a floating-point number, scanf looks for a plus or minus sign (optional). followed by a series of digits (possibly containing a decimal point). followed by an exponent (optional). An exponent consists of the letter e (or E), an optional sign, and one or more digits. The te, % f, and %g conversions are interchangeable when used with scanf: all three follow the same rules for recognizing a floating-point number. When scanf encounters a character that can't be part of the current item, the character is "put back" to be read again during the scanning of the next input item or during the next call of scanf. Consider the following (admittedly pathological) arrangement of our four numbers: 1-20.3-4.0e3 Let's use the same call of scanf as before: Here's how scanf would process the new input: . Conversion specification: %d. The first nonblank input character is 1: since integers can begin with 1. scanf then reads the next character, -. Recogniz- ing that - can't appear inside an integer. scanf stores l into i and puts the character back. Conversion specification: %d. scanf then reads the characters-, 2, 0, and (period). Since an integer can't contain a decimal point, scanf stores -20 into j and puts the. character back . Conversion specification: f, scan f reads the characters . , 3, and-. Since a loating-point number can't contain a minus sign after a digit, scanf stores 0.3 into x and puts the character back. . Conversion specification: %f. Lastly, scanf reads the characters-, 4, .. o, e, 3, and o (new-line). Since a floating-point number can't contain a new-line character. scanf stores -4.0 x 103 into y and puts the new-line character back. In this example. scanf was able to match every conversion specification in the format string with an input item. Since the new-line character wasn't read, it will be left for the next call of scanf 3.2 The scanf Function 45 Ordinary Characters in Format Strings The concept of pattern-matching can be taken one step further by writing format strings that contain ordinary characters in addition to conversion specifications. The action that scanf takes when it processes an ordinary character in a format string depends on whether or hot it's a white-space character. White-space characters. When it encounters one or more consecutive white- space characters in a format string, scanf repeatedly reads white-space char- acters from the input until it reaches a non-white-space character (which is "put back"). The number of white-space characters in the format string is irrelevant; one white-space character in the format string will match any num- ber of white-space characters in the input. (Incidentally. putting a white-space character in a format string doesn't force the input to contain white-space characters. A white-space character in a format string matches any number of white-space characters in the input, including none.) Other characters. When it encounters a non-white-space character in a format string, scanf compares it with the next input character. If the two characters match, scanf discards the input character and continues processing the for- mat string. If the characters don't match, scanf puts the offending character back into the input, then aborts without further processing the format string or reading characters from the input. For example, suppose that the format string is "%d/ d". If the input is #5/#96 scanf skips the first space while looking for an integer, matches %d with 5. matches / with / , skips a spare while looking for another integer, and matches with 96. On the other hand, ifthe input is scanf skips one space, matches %d with 5, then attempts to match the / in the format string with a space in the input. There's no match, so scanf puts the space back: the./.96 characters remain to be read by the next call of scanf. To allow spaces after the first number, we should use the format string " d /%d" instead. Confusing printf with scanf Although calls of scanf and printf may appear similar, there are significant differences between the two functions; ignoring these differences can be hazardous to the health of your program. One common mistake is to put & in front of variables in a call of printf printf("ad tdin. &i, &j) WRONG/ ownloads/C%20Programming,%20A%20Moder%20Approach%20-%20K%20N.%20 King pdf Chapter 3 Formatted Input/Output Fortunately. this mistake is fairly easy to spot: printf will display a couple of odd-looking numbers instead of the values of i and j Since scanf normally skips white-space characters when looking for data items, there's often no need for a format string to include characters other than conversion specifications. Incorrectly assuming that scanf format strings should rescmble printf format strings-another common error-may cause scanf to chne n negedys lar's se whax happall or scanf is executed: scanf ("%d. %d", &1, &j); scanf will first look for an integer in the input. which it stores in the variable i. scanf will then try to match a comma with the next input character. If the nex input character is a space, not a comma, scanf will terminate without reading a value forj Although printf format strings often end with , putting a new-line character at the end of a scanf format string is usually a bad idea. To scanf, a new-line character in a format string is equivalent to a space: both cause scanf to advance to the next non-white-space character. For example, if the format string is "%d ", scanf will skip vvhite space, read an integer, then skip to the next non- white-space character. A format string like this can cause an interactive program to hang" until the user enters a nonblank character PROGRAM Adding Fractions To illustrate scanf's ability to match patterns, consider the problem of reading a umera- fraction entered by the user. Fractions are customarily written in the fom torldenominator. Instead of having the user enter the numerator and denominator of a fraction as scparate integers, scanf makes it possible to read the entire frac- tion. The following program, which adds two fractions, illustrates this technique. addfrac.c Adds two fractions/ #include int main(void) int numi, denoml, num2, denom2, result_num, result_denom printf("Enter first fraction: ") printf (Enter second fraction: scant ("sd/td", &num2,&denom2) result num num1 denom2 num2 denom1

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Processing Fundamentals Design And Implementation

Authors: David M. Kroenke

5th Edition

B000CSIH5A, 978-0023668814

More Books

Students also viewed these Databases questions

Question

3. Explain the forces that influence how people handle conflict

Answered: 1 week ago