I follow the book C programing second edition and try to output this code:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF)
++nc;
printf("%1d\n", nc);
}
and I can't figure out why I don't have any output.
I work on crunchbang++ and to create the output I entered in the terminal:
cc -ansi file.c
then
./a.out
but when I enter characters I have a blank response.
I don't want just the working code, but an explanation, because I really want to learn how it works.
#include <stdio.h>
int main(void)
{
long num_of_chars = 0;
while(getchar() != '\n'){
++num_of_chars;
}
printf("%ld\n", num_of_chars);
}
EOF means End of File.
EOF is not a character. It is a state which indicates no more characters to read from a file stream. When you enter EOF command from the terminal, you are signalling the OS to close the input stream, not putting in a special character.
Now either you can change your code to read a file, emulate EOF, or cancel while loop on different character.
Above example will end while loop on new line.
$ ./main
This is a test
14
Edit:
Tested on linux with EOF.
Ctrl + Z will outright stop the program.
Ctrl + D will output num_of_chars if pressed twice or by doing Enter and then Ctrl + D.
Edit 2:
With EOF.
printf foo | ./your_program Output: 3
echo foo | ./your_program Output: 4 (echo adds newline caharacter)
Related
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void eat() // clears stdin upto and including \n OR EOF
{
int eat;while ((eat = getchar()) != '\n' && eat != EOF);
}
int main(){
printf("\n COMMAND : "); char cmd[21]=""; scanf("%20s",cmd);
if(strcmp(cmd,"shell")==0||strcmp(cmd,"sh")==0)
{
getchar(); // absorb whitespace char separating 'shell' and the command, say 'ls'
while(1)
{
printf("\n sh >>> "); // print prompt
char shellcmd[1024]=""; // str to store command
scanf("%1023[^\n]",shellcmd); eat(); // take input of command and clear stdin
if(strcmp("close",shellcmd)==0||strcmp("x",shellcmd)==0)
break;
else
system(shellcmd);
}
}
}
In the code, some anomalous behavior is occurring which I'm unable to catch.
Upon entering sh ls and pressing [ENTER], the expected response is:
1st scanf() stored sh in cmd[] and leaves ls\n in stdin.
getchar() takes up the space.
printf() prints \n sh >>> to Terminal
second scanf() stores ls in shellcmd[], leaves \n in stdin
eat() reads the \n from stdin, leaving it empty
system("ls") is executed
I.e. results should be like this:
COMMAND : sh ls
sh >>>
file1 file 2 file3 ...
sh >>> | (cursor)
BUT
What I get:
COMMAND : sh ls
file1 file2 file3 ...
sh >>>
sh >>> |
Apparently, the 2nd scanf() and shell() are executing before printf() , or at least that's my assumption.
What's amiss?
Compiled on Clang and GCC with cc -Wall -Wextra -pedantic and tested on bash on MacOS as well as Linux
As you can find in the man page:
If a stream refers to a terminal (as stdout normally does) it is line buffered
So you might experience a delay in seeing the message printed by printf whenever it doesn't contain a newline. On the other end, the previos message is displayed as soon as the leading newline of the next printf is sent.
Solutions:
Add a newline at the end your message printf("\n sh >>> \n");
Force the current buffer to be displayed even in absence of a newline by calling flush() function (fflush(stdout))
Change the current stdout buffering behavior with setvbuf() function
setvbuf(stdout,NULL,_IONBF,0);
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.
i am learning c language, and the program is about counting no of characters.
here is code
#include <stdio.h>
int main(void) {
// your code goes here
double nc;
for (nc=0;getchar() != EOF;nc++);
printf("%.0f\n", nc);
return 0;
}
input
''
input in none.
the output which I am getting is 1.
online compiler result
shouldn't be output equal to 0, not 1.unable to understand why is this coming.
thanks
if you put a bit more effort in yor programming adding couple of lines of code everything would be clear:
#include <stdio.h>
int main(void) {
// your code goes here
int nc;
int c;
for (nc=0;(c = getchar()) != EOF;nc++)
{
printf("The char is '%c' code: 0x%02x\n", c >= 32 ? c : '.', c);
}
printf("%d\n", nc);
return 0;
}
https://ideone.com/jfGK7h
And the mistery is solved. You have pressed the enter in the ideone input box and you have a new line there.
How did you input that input?
If you hit the <enter> key at the keyboard, then you got a single \n char, leading to that response.
Try this:
$ a.out
<Ctrl-D>
0
$ _
($ is the prompt, and <Ctrl-D> is the way to produce no input from a unix terminal) Of course, a.out is the name of your program (you didn't show how it is called)
BTW, why do you end the output in a \t in printf() ??? \t is a tab character, not a new line.... 8-.
This question already has answers here:
End of File (EOF) in C
(3 answers)
Closed 7 years ago.
When I use this code, I can type into the command line and get back what I typed:
main() {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
}
Output:
~/code/c $ ./a.out
one
one
two
two
But when I use this code, it only works when I pipe in data, not when I type data into the command line:
main() {
int nc;
nc = 0;
while (getchar() != EOF) {
nc++;
}
printf("%d\n", nc);
}
When I pipe data in from a text file:
~/code/c $ ./a.out < practice.txt
14
When I try to input data from the command line:
~/code/c $ ./a.out
one
two
three
What's going on?
The while loop never exits since while (getchar() != EOF) is always true. After you're done with the input, press Cntrl+D for Linux or Ctrl+Z for Windows to indicate EOF.
Like everyone mention, you program doesn't stop. The while loop needs a condition to stop. you have to either use CTRL+Z (Win) or CTRL+D(Unix) to stop it, When you pipe it actually sends that character for you. Because EOF is END_OF_FILE. So when you hit the end of your file. the OS sends that character for you.
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++ ;
}