Joseph Haugh
University of New Mexico
Book Version:
void main(void) {
int c;
int numberOfLines = 0;
while((c = getchar()) != EOF) {
if(c == '\n') numberOfLines++;
}
printf("%d\n", numberOfLines);
}
Modified Version:
void main(void) {
int numberOfLines = 0;
int c = getchar();
while(c != EOF) {
if(c == '\n') numberOfLines++;
c = getchar();
}
printf("%d\n", numberOfLines);
}
Why is getchar called twice?
#define IN 1
#define OUT 0
void main(void) {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while((c = getchar()) != EOF) {
++nc;
if (c == '\n') ++nl;
if(c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if(state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
Coding style in textbook:
#define IN 1
#define OUT 0
void main(void) {
/* Body of function on next slides */
}
void main(void) {
int charCount = 0;
int totalCharCount = 0;
int wordCount = 0;
int totalWordCount = 0;
int wordState = OUT;
int lineCount = 1;
int c = getchar();
while (c != EOF) {
/* BODY ON NEXT SLIDE */
}
printf("%d lines, %d words, %d characters\n",
lineCount-1, totalWordCount, totalCharCount);
}
if (charCount == 0) {
printf("(%2d) ", lineCount);
}
if (c == '\n') {
printf("[%d, %d]\n", wordCount, charCount);
charCount = 0;
wordCount = 0;
wordState = OUT;
lineCount++;
}
else {
/* BODY ON NEXT SLIDE */
}
else { /* char just read not '\n' */
charCount++;
totalCharCount++;
printf("%c", c);
if (c == ' ' || c == '\n' || c == '\t') {
wordState = OUT;
}
else if (wordState == OUT) {
wordState = IN;
wordCount++;
totalWordCount++;
}
}
c = getchar();
Add some variables to track with:
int mostCharLineNum = 0;
int mostCharCount = 0;
int mostWordLineNum = 0;
int mostWordCount = 0;
Output the results at the end:
printf("%d lines, %d words, %d characters\n",
lineCount-1, totalWordCount, totalCharCount);
printf("Line %d has the most words with %d\n",
mostWordLineNum, mostWordCount);
printf("Line %d has the most characters with %d\n",
mostCharLineNum, mostCharCount);
At the end of lines, check for new longest line:
if (c == '\n') {
printf("[%d, %d]\n", wordCount, charCount);
if(charCount > mostCharCount) {
mostCharCount = charCount;
mostCharLineNum = lineCount;
}
if(wordCount > mostWordCount) {
mostWordCount = wordCount;
mostWordLineNum = lineCount;
}
charCount = 0;
wordCount = 0;
wordState = OUT;
lineCount++;
}
else {