Yahoo Interview Question
Software Engineer / DevelopersWe start reading the file until eof is reached.
Every character we read increases the number of characters by 1.
Every new line character increases the number of lines by 1.
And every new line and set of space characters increases the number of words by 1.
So by using just one read character command in c,c++ or java we can count all of them.
This topic also appears in a Google interview.
The tricky point is to handle multiple spaces between two words.
<pre lang="c" line="1" title="CodeMonkey62191" class="run-this">#include<stdio.h>
main(){
FILE *fp;
fp = fopen("input.txt","r");
char read[1000];
int lines=0,words=0,characters=0;
while(fgets(read,1000,fp)){
lines++;
int i=0;
while(read[i]){
if(read[i++]==' ')
words++;
else
characters++;
}
}
printf("%d %d %d\n",lines,words+1,characters);
getchar();
}
</pre><pre title="CodeMonkey62191" input="yes">
</pre>
I think the interviewer is asking for the UNIX command wc.
- BXH September 13, 2010