08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7.12 Fetch the Next Integer

Chapter 7 ■ Functions

Previously, we wrote Program P6.13, which read the data character by character, constructed and

stored the next integer found in a variable, and finally printed the integer.

Let us now write a function, getInt, which reads the data character by character and returns

the next integer found. The function does not take any arguments but the brackets must still

be written after the name. The code is essentially the same as in P6.13, except that we use the

predefined function isdigit. Here is getInt:

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

Note that

while (ch < '0' || ch > '9')

of program P6.13 is replaced by

while (!isdigit(ch))

and

while (ch >= '0' && ch <= '9')

is replaced by

while (isdigit(ch))

We believe this makes the program a little more readable.

The function needs the variables ch and num to do its job; ch holds the next character in the

data and num holds the number constructed so far. We declare them within the function, making

them local variables. This way, they will not conflict with any variables with the same names

declared anywhere else in the program. This makes the function self-contained – it does not

depend on variables declared elsewhere.

The function can be used as in

id = getInt();

191

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!