Tuesday, 12 December 2017

c - A better way to print each word in a newline without using libraries (apart from stdio.h)?

I'm trying to write a program that takes from the standard
input stream a sentence, and based on the definition that a word is everything that is
between "spaces"; "spaces" being the space character, tab character or newline
character, so, for example, if the input stream is hey there this is some
test
, the output should
be



hey
there
this
is
some
test


Here
is my try:



#include


#define TRUE 1
#define FALSE
0

#define IS_SPACE(c) ((c) == ' ' || (c) == '\t' || (c) ==
'\n')

int main() {

for(int c, inWord = FALSE;
(c = getchar()) != EOF;)
if(!IS_SPACE(c)) {
putchar(c);

inWord = TRUE;
}
else if(inWord) {

putchar('\n');
inWord = FALSE;
}

return
0;
}


But I
don't like this approach because I am manually entering TRUE and FALSE to
inWord when it can be automatically be done by
inWord = !IS_SPACE(c), but I don't know how to modify the code
to make just one call to IS_SPACE without creating another
temporal variable.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...