Я знаю, что я обманываю, но этот пример показывает, как функции более высокого уровня делают программы более понятными.scanf
'%s
преобразование делает разделение слов для нас.В примере используется символ подавления присваивания *
, который устраняет необходимость предоставлять место для произвольно длинных слов, которые мы на самом деле не хотим знать.
#include <stdio.h>
int wordcount = 0;
int main(void) {
while(scanf("%*s") != EOF)
{
wordcount++;
}
printf("%d\n", wordcount);
return 0;
}
Если бы мне пришлось свернуть его самостоятельно,Я бы написал подпрограммы.Посмотрите, как чисто выглядит main
#include <stdio.h>
/** @return 1 if c is whitespace, else 0. */
static int isWhite(int c);
/** When this function returns, c is either EOF or non-whitespace.
@return c
*/
static int readWhite();
/** When this function returns, c is either EOF or whitespace.
@return c
*/
static int readWord();
int main(void) {
int wordcount = 0;
while(readWhite() != EOF)
{
wordcount++;
readWord();
}
printf("%d\n", wordcount);
}
//////////////////////////////////////////////////////
static int isWhite(int c)
{
return c == '\n' || c == '\t' || c == ' ';
}
//////////////////////////////////////////////////////
static int readWord()
{
int c;
while((c = getchar()) != EOF && !isWhite(c))
{
; // this statement intentionally left blank
}
return c;
}
//////////////////////////////////////////////////////
static int readWhite()
{
int c;
while((c = getchar()) != EOF && isWhite(c))
{
; // this statement intentionally left blank
}
return c;
}