L-19 MCS 260 Wed 3 Oct 2001
In this lecture we saw another application of a macro of
ctype.h and arithmetic with ASCII codes.
Important is the technique of keep track of current and previous
character.
/* L-19 MCS 260 Wed 3 Oct 2001 : scanning input for numbers
Suppose we have an input stream of characters, like
a be 124 2d dd3 d3 342,4353 023 aa 0 dd ( 232 dda
then the output contains only the integer numbers :
124 2 3 3 342 4353 23 0 232
This program is best applied with redirection, putting the
input in a file, say "stream" and running as a.out < stream. */
#include<stdio.h>
#include<ctype.h>
int main(void)
{
int current;
int previous = ' ';
int nb = 0;
while ((current = getchar()) != EOF)
{
if isdigit(current)
nb = 10*nb + current - '0';
else if isdigit(previous)
{
printf(" %d", nb);
nb = 0;
}
previous = current;
}
return 0;
}
The technique of current and previous character is again
applied in the following program.
/* L-19 MCS 260 Wed 3 Oct 2001 : counting words of the input.
In an input stream of characters, we consider words anything
that is separated by spaces. If the input is something like
this is a test
then the program counts four words. Observe that more than
one space can separate the words.
This program is best applied with redirection, putting the
words in a file, say "words" and running as a.out < words. */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int current;
int previous = ' ';
int cnt = 0;
while ((current = getchar()) != EOF)
{
if (isspace(previous) && !isspace(current)) cnt++;
previous = current;
}
printf("Number of words : %d\n", cnt);
return 0;
}
An extension of this program is to reformat the input so
that every word is separated by exactly one space.