简体   繁体   中英

How to exit the character counting program (I'm using dev c++)

I have a problem when runnig the character counting program:

#include<stdio.h>
main()
{
   double nc  ;      
   for( nc = 0; getchar() != EOF; ++nc)
         ;
   printf("%.0f\n", nc) ;
}

I wrote it exactly the same as the code on my textbook(the c programming language 2nd edition by Brian W. Kernighan & Dennis M. Ritchie) and using the dev c++ to edit and compile

When running this program, I found that when I type a string of characters and then press ENTER, it simply shifted to the next line, how am I supposed to do to tell the machine that my input terminates and exit the program and receive the nc ?

You loop over the string you entered with the keyboard. You will end the loop as soon as a EOF (end of file) character is read. On Unix, Linux, BSD and so on you can signal a end of file by pressing CONTROL-D. On Windows it's CONTROL-Z. On Mac it should be CONTROL-D because it's close to BSD Unix. (But i'm not sure).

If you need to end the for loop by pressing "ENTER" a test for EOL (end of line) might help.

Edited

for( nc = 0; getchar() != '\n'; ++nc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM