I have to print the no. of lines entered by the user, but following code is not working:
If anybody could help.Code:void main() { int c,a=0; while((c=getchar())!=EOF) if(c=='\n') a++; printf("%d",a); getch(); }
Thanx!
I have to print the no. of lines entered by the user, but following code is not working:
If anybody could help.Code:void main() { int c,a=0; while((c=getchar())!=EOF) if(c=='\n') a++; printf("%d",a); getch(); }
Thanx!
Last edited by able; 06-18-2006 at 02:45 AM.
That'll return the number of characters entered. Once you get a character (c), check if it's equal to a newline ('\n').
Also: Not "void main()" - It's "int main()"...
Edit: Also, put your c=getchar() in parenthesis. ie:
!= has higher precedence than =, so without parenthesis c will always be 1 or 0.Code:while((c = getchar()) != EOF)
long time; /* know C? */
Unprecedented performance: Nothing ever ran this slow before.
Any sufficiently advanced bug is indistinguishable from a feature.
Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
The best way to accelerate an IBM is at 9.8 m/s/s.
recursion (re - cur' - zhun) n. 1. (see recursion)
Don't forget to #include <stdio.h>, for the prototype of printf() and the definition of getchar(), etc.
You shouldn't use getch(); it's non-standard. See this. If you do use it, include <conio.h>.
[edit] As for void main(): http://faq.cprogramming.com/cgi-bin/...&id=1043284376 [/edit]
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
I've included all headers. I dunno why its not working. Do we have to input some special character(for EOF) to end input? I just keep pressing enter to end input but nothing happens. Cant anybody help??
Seems logical to me since EOF is a character inserted by the OS at the end of a file.
> I just keep pressing enter to end input but nothing happens. Cant anybody help??
EOF != enter.
How you signal EOF on stdin depends on your OS (mostly)
For DOS / win32 console, type in ctrl-z (that's hold down ctrl and press z) at the start of a line, and perhaps press return after it.
For Unix / Linux, it is usually ctrl-d
> Seems logical to me since EOF is a character inserted by the OS at the end of a file.
EOF is a state, not a character.
Zero length files can return EOF just as well as any other file.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.