Unable to print number of characters using getchar, in Ubuntu - c

I am new to C, and to Ubuntu. I wrote a very simple program to count the number of characters using while and getchar(). The program is:
#include <stdio.h>
main() {
int i;
int c= 0;
while ( ( i = getchar() ) != EOF ){
c++ ;
}
printf( "%d characters\n" , c) ;
return 0;
}
I saved it and compiled it using gcc c1.c -o c1. No errors reported. I executed the program using ./c1 . I give the input as daniweb then I press enter, but the count is displayed. What went wrong? Is it infinite loop? How does getchar() determine EOF when input is given from keyboard?

On the terminal you can send EOF to an application by pressing Ctrl+D. You can also do something like this:
echo "blablub" | ./yourprogram
To count how many characters are in blablub. In this case EOF is sent automatically.

Pressing enter sends a new line character to your program, not EOF. As others have mention already, use Ctrl+D to send EOF. If you want to stop reading characters on newline, change your while loop to this:
while ( ( i = getchar() ) != '\n' ){
c++ ;
}

Related

Using EOF and getchar() to count the number of characters

I am trying to write a program for counting the number of characters in C. Below is my program:
#include <stdio.h>
int main(void){
// long nc;
// for(nc = 0; getchar() != EOF; nc++);
// printf("%ld\n", nc);
long nc;
nc = 0;
while(getchar() != EOF){
++nc;
}
printf("%ld\n", nc);
return 0;
}
When I execute the above program using the input :-
123<Enter>
then I press the control + ^d on my Mac to represent EOF, I am getting the output as 4D instead of just 4. Can anyone please tell me why I am getting D in my output?
[Turning my comment into an answer]
The "problem" is that the terminal program itself writes the output ^D as response to the Ctrl-D.
With the original output of your program (without the extra leading newline) the program writes its output 4 over the ^ written by the terminal. The (trailing) newline from the program then makes the terminal go to the next line where the shell takes over and writes it prompt.
This will make it seem like the output of your program is 4D.
As a possible solution, you might want to check the settings of your terminal program to see if its own output could be disabled.

should i follow this book "c programming language 2nd edition" but some code in it doesn't work

I found this book have many people suggest for newbie, but some code on it doesn't work, although I code it exactly like the code in the book but it still don't work
#include <stdio.h>
main()
{
int a ;
for (a = 0; getchar() != EOF ; ++a);
printf ("%d",a);
}
It looks like after the loop it ends immediately, code after the loop is not executed.
Is this book is too old? Is there any another book for self learning c programming?
int main( void )
{
int a ;
for (a = 0; getchar() != EOF ; ++a);
printf ("%d\n",a);
return 0;
}
On Unix platform run this code and when you want to exit introduce EOF by ctrl+d, if you are on windows then EOF is introduced by ctrl+z
So basically when you exit you will get the count of number of times your loop ran.
If you want to print out each input then you need to get rid of the ; at the end of for loop
int main( void )
{
int a ;
for (a = 0; getchar() != EOF ; ++a)
printf ("%d\n",a);
return 0;
}
I strongly suspect that the console closes immedeately after the loop ends. Try to insert something like system("pause") to prevent the console from closing.
The loop loops until you type EOF and prints the number of characters typed so far. To type EOF, you have to hit ctrl-z and return (in a test I had to do this after a return, so return, then ctrl-z, then return). If the console closes directly after the ctrl-z, you can add this system("pause") to wait for another key afterwards, so you see the output.

Controlling getchar() in while loop

Say I have a simple while loop to enter **1*0* characters.
After more than 10, I want the loop to stop.
However, the break seems not to take effect.
Only when I press Enter it ends. Can anyone explain please?
int count = 0;
int numchars = 10;
ch = getchar();
while( ch != '\n' && ch != '\0' ) {
array[count] = ch;
count++;
if ( count > numchars ){
break;
}
ch = getchar();
}
Thanks.
stdin is not your tty, even when your tty is connected to stdin. Unless you put your tty in raw mode, the program does not see any data at all until you hit return. When you hit return, all of the data on the line is sent to the program, which then enters the loop and reads characters until it breaks out of the loop. If you really want the program to see characters as you press them, you will need to do a lot more work. Look into libraries like ncurses first, and then do some research on how to put a tty into raw mode. And then write the simple program that requires the user to hit return.
use getch() or getche() instead of getchar() and numchars=9 for 10 characters.

Getchar() doesn't work?

I was confused by the getchar() function, so I searched this great website and read all the relative topics and read about getchar() in K&R book. But when I ran the code, typed a word on the console screen, and hit enter, nothing happened. I expected the number of characters to be displayed.
#include<stdio.h>
int main(void)//doesn't work??
{
int c ;
int count ;
while ( ( c = getchar() ) != EOF )
count ++ ;
printf( "%d characters\n" , count ) ;
return 0;
}
I think its because you are pressing enter and expecting the loop to stop.
The condition
while ( ( c = getchar() ) != EOF)
will only be false on Windows when you press Ctrl + Z.
On UNIX it is Ctrl + D I think, so it should be Ctrl + D if you are using Ubuntu.
If you want the loop to stop on pressing enter try checking for the '\n' character instead.
If you're using windows, ENTER doesn't correlate to EOF.
This question might explain this for you:
Why doesn't getchar() recognise return as EOF on the console?
Either replace the EOF with '\n', or send EOF using Ctrl+D on Unix-like systems (or Ctrl+Z on Windows as mentioned by others).
Edit: And the count is wrong because you have not initialized the variable to 0. The value of an uninitialized variable will be undefined, and your compiler should warn you about this.
EOF means end of file but you did not open any file so how you expect it would work ?
int main (void) \\ no problem using these . it just says no arguments to main
example
int main( )
{
int a=40;
main(a); \\ you wont find any error with these
}
int main( void )
{
int a=40;
main(a); \\ you get error saying main function cant take arguments
}
main( ) it can take infinite arguments and whereas main(void) none arguments
Thats why when you use
getch(a) or clrscr(1) your passing arguments to these functions so you get error
because they are defined as clrscr( void ) getch (void )
strlen(char *) \\ can take only one argument
You can check out them in header files
Try these
c = 0; count = 0 ; initialize it so that you wont have any garbage value
while ((c=getchar)!='\n') or may be its AScll value
while ((c=getchar)!=13)
FILE *p;
p=fopen("hello.txt","r");
while ( c = getc(p) != EOF ) \ When it returns end of file while loop exits
Say You have these content in hello.txt
"hello world My name text file"
for every loop c has the character like h,e,l and when it returns to end it exits
So EOF mostly used with files I Hope you got the point

count blanks from the input

I wrote a program to count blanks. I can compile it and run it, it's fine. But why it does not display the count?
#include<stdio.h>
main()
{
int count=0;
int c;
while((c=getchar())!=EOF)
{
if(c == ' ') count++;
}
printf("%d\n",count);
}
Your exact code (errors and all) works as you'd expect at ideone.
How do you terminate the input? To send an EOF signal to your program from the console type, at the beginning of a line, CtrlD in Linux or CtrlZ in Windows.
Also try to run with redirected input. Something like
yourprog < data.txt
or
echo one two three four | yourprog
You're probably not getting the EOF that you expect from input. You may be expecting the Enter key to be EOF, which will not happen. Have you tried using one of the ctrl+ combinations such as Z or D (depending on OS) to send the EOF ?

Resources