Exercise 5-1 (getint)

Chapter_5 Exercise_5-2







Exercise 5-1     K&R, p. 97


Exercise 5-1. As written, getint() treats a + or - not followed by a digit as a valid representation of zero. Fix it to push such a character back on the input.




CONTENTS:     integers.txt     getint.c




integers.txt         download


-123 254 120356 145879 +56 +963 -89 78 3254 -852
0123 142587 -8526 45678 231054 52368 +0236 789 2 0





getint.c     K&R, p. 96-97         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

#define SIZE 100 // array size

int getint(int *); // get the next int from input

int main()
{
int i, n, array[SIZE];

for (n = 0; n < SIZE; n++)
{
i = getint(&array[n]);
if (i == EOF || i == 0) // end of input or not a number
{break;} // out of for()
}
printf("Array size: %d\n", n);
for (i = 0; i < n; i++) // print array
{printf("%d%c", array[i], (i % 10) == 9 ? '\n' : ' ');}
if (n % 10 != 0) {putchar('\n');}

return 0;
}

#include <ctype.h> // for isspace(), isdigit()

int getch(void);
void ungetch(int);

int getint(int *pn) // get the next int from input
{
int c, sign;

while (isspace(c = getch())) // skip whitespace
{}
if (c == EOF)
{return c;} // return EOF;
if (!isdigit(c) && c != '+' && c != '-')
{
ungetch(c);
return 0; // not a number
}

sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
{c = getch();}
if (!isdigit(c))
{
ungetch(c);
return 0; // not a number
}

for (*pn = 0; isdigit(c); c = getch())
{
*pn = 10 * *pn + (c - '0');
}
*pn *= sign;

ungetch(c); // if (c == EOF), it will be returned by the next call to getint()

return 1; // valid integer found
}

// buffer for ungetch():
int buf = EOF-1; // not a real character, not even EOF

int getch(void) // get a (possibly pushed-back) character
{
if (buf < EOF)
{
return getchar();
}

int temp = buf; // buf >= EOF
buf = EOF-1; // reset buf

return temp;
}
// push character back on input (make it available for the next getch()):
void ungetch(int c)
{
buf = c;
}
/*
gcc getint.c -o getint
./getint
a
Array size: 0

./getint
a 1
Array size: 0

./getint
1 a
Array size: 1
1

./getint
-.2
Array size: 0

./getint
1.2
Array size: 1
1

./getint
0 // Type Enter, then Ctrl^D in Linux or Ctrl^Z + Enter in Windows (EOF)
Array size: 1
0

./getint
-1 +02
Array size: 2
-1 2

./getint
0 1 2 3 4 5 6 7 8 9
Array size: 10
0 1 2 3 4 5 6 7 8 9

./getint
0 1 2 3 4 5 6 7 8 9 10
Array size: 11
0 1 2 3 4 5 6 7 8 9
10

./getint < integers.txt
Array size: 20
-123 254 120356 145879 56 963 -89 78 3254 -852
123 142587 -8526 45678 231054 52368 236 789 2 0
*/









Chapter_5 BACK_TO_TOP Exercise_5-2



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo