08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7 ■ Functions

This fetches the next positive integer from the input, regardless of how many and what kind of

characters come before it, and stores it in id. Recall that scanf("%d", &id) works only if the next

integer is preceded by zero or more whitespace characters. Our getInt is more general.

We test it by rewriting Program P4.2, which requests two lengths given in meters and

centimeters and finds the sum. We observed then that the data must be entered with digits only.

If, for instance, we had typed 3m 75cm we would have gotten an error since 3m is not a valid integer

constant. With getInt, we will be able to enter the data in the form 3m 75cm. The new program is

shown as Program P7.11.

Program P7.11

//find the sum of two lengths given in meters and centimeters

#include <stdio.h>

#include <ctype.h>

int main() {

int m1, cm1, m2, cm2, mSum, cmSum, getInt();

printf("Enter first length: ");

m1 = getInt();

cm1 = getInt();

printf("Enter second length: ");

m2 = getInt();

cm2 = getInt();

mSum = m1 + m2; //add the meters

cmSum = cm1 + cm2; //add the centimeters

if (cmSum >= 100) {

cmSum = cmSum - 100;

mSum = mSum + 1;

}

printf("\nSum is %dm %dcm\n", mSum, cmSum);

} //end main

int getInt() {

char ch = getchar();

// as long as the character is not a digit, keep reading

while (!isdigit(ch)) ch = getchar() ;

// at this point, ch contains the first digit of the number

int num = 0;

while (isdigit(ch)) { // as long as we get a digit

num = num * 10 + ch - '0'; // update num

ch = getchar();

}

return num;

} //end getInt

192

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!