Basic character counting in C [duplicate] - c

This question already has answers here:
Why doesn't getchar() recognise return as EOF on the console?
(8 answers)
Testing getchar() == EOF doesn't work as expected
(2 answers)
Closed 5 years ago.
Having trouble getting an actual count, but I'm not seeing what I'm doing wrong.
I type in a word, hit enter, then nothing happens and it keeps running.
int main(void)
{
double nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf ("%.0f\n", nc);
}

When reading from an interactive console input, getchar() will not return EOF just because the user stops typing or presses return, it will if necessary wait for the user to enter something new on the keyboard. So, the for-loop is not terminated.
You have to use a special key combination (dependent on the operating system used) to signal end-of-file or check for some other input to terminate the loop (like end-of-line, for example)

As noted, EOF will not be true until ^D is entered. Terminate on that, but also check for the newline character. Check this older Question for some good background on this here:
getchar() != EOF
Here is the program written using ints and checking for newline or EOF
// Customize AT_END Macro to return true based on some condition
#define AT_END(ch) (((ch)=='\n') || ((ch)==EOF))
int main(void)
{
int inpChar = getchar();
int nc = 0;
while (!AT_END(inpChar)) {
nc++;
inpChar = getchar();
};
printf("Number of chars=%d\n", nc);
}

Related

getchar() keeps returning EOF value when called second time

I have trouble understanding getchar() and EOF.
I was trying to run this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char c;
int a = 0; //no. of characters
while (1) {
c = getchar();
if (c == EOF) {
// printf("%i",c);
break;
}
putchar(c);
++a;
}
printf("%i", a);
int b;
while ((b = getchar()) != EOF) {
putchar(b);
}
printf("here"); // to check wether the code written after the loop is executed
}
I terminated the first loop by pressing Ctrl-D twice, I found many posts explaining the reason for this. But whenever I try to call the getchar() function after the first loop it keeps returning EOF, even though that would have been already read by the last call in the first loop.
Code editor - VSCode
OS - macOS
You must define c as an int to accommodate for the full range of possible return values from getchar(), namely all values of type unsigned char and the special negative value EOF (usually defined as (-1)).
On most unix systems, when Ctrl-D is typed in the terminal in canonical mode, whatever input has been buffered by the terminal is sent to the process. In your case, it causes the input to be echoed. If there is no such input pending, the terminal sends zero bytes to the process, which is interpreted by the OS as the end of file. Hitting Ctrl-D twice in a row, or more precisely at the beginning of a read request, does not enter an EOF byte, it signals the end of file to the reading process, hence any further attempt at reading from the stream will return EOF immediately without requesting more user input from the terminal.

Usage of EOF in C

Output
Code:
#include<stdio.h>
main()
{
int c;
printf("Enter any charachter!: ");
while((c = getchar()) != EOF) {
putchar(c);
printf("%d\n", (c = getchar()) != EOF);
}
}
I've tried to test out EOF in C and I'm having a difficult time with it. I've wanted to get the value of EOF and found out that it is -1.
I wrote a simple program using getchar() and putchar().
I have added the screenshot of the program and output. Output doesn't make any sense to me.
As you can see I'm trying to get a character and display it using getchar() and putchar(). And I'm trying to print out the value of the condition used in the while loop. To check the EOF I'm deliberately entering -1 as input. putchar() prints out -1 and then the final printf statement confuses me. I enter -1 for getchar() but 1 displayed meaning c is not equal to EOF. But I thought -1 is EOF.
And I don't understand why 11 is also displayed. I'm using codeblocks IDE.
Please help me. Thanks in advance.
EOF isn’t a character, and it isn’t read from the stream. It’s just the return value indicating that there is no more input on that stream. You can signal an EOF by typing CtrlD on *nix or CtrlZ on Windows.
getchar takes input one character(byte) at a time. so when you input '-1' it is treated as a character array input and first getchar takes input only '-' and second one takes input '1'. Thus you are not getting your desired output. Also putchar is designed to print one character at a time. So it might not work properly too. You can change your code following way to make it work.
int c;
while(scanf("%d", &c)!=EOF) { //to ensure there is some input value as scanf will return EOF when input stream finishes.
printf("%d\n", c);
if(c == EOF) {
printf("c is equal to EOF\n");
break;
}
}

Why loop is not getting terminated? [duplicate]

This question already has answers here:
What is EOF in the C programming language?
(10 answers)
Closed 6 years ago.
int main()
{
int c;
c = getchar();
while (c!=EOF){
putchar(c);
c=getchar();
}
return 0;
}
in above code when I input value -1 why the loop doesn`t get terminated.
value of EOF = -1 I got from this code,
main()
{
printf("EOF is %d\n",EOF);
}
code get terminated when I use Ctrl+D,is there any other way to terminate the same code without using Ctrl+D.
Because typing -1 on console doesn't generate EOF. Instead getchar() reads it as two separate characters '-' and '1'.
If you want to terminate it with -1 input then you have to keep track of two characters and compare them to exit the loop instead of comparing against EOF. But that is really not equivalent of generating an EOF.
Another option to terminate is to redirect standard input to a file via input redirection < in console. When the reading from input file ends it will signal an EOF.
If you want to loop out of the code without pressing ctrl+D then there are multiple ways of doing it. I will show you the easiest and inefficient way of doing it using a basic if condition. Go through the code and if you have any doubt please feel free to comment on it.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int c;
c = getchar();
while ((c != EOF))
{
if (c == 'i')
break;
putchar(c);
c = getchar();
}
return 0;
}

A loop to read characters from console till EOF character is encountered using getchar() is not exiting when EOF character is encountered [duplicate]

This question already has answers here:
Why two EOF needed as input? [duplicate]
(2 answers)
Why do I require multiple EOF (CTRL+Z) characters?
(5 answers)
Closed 7 years ago.
Here is program to read character from the console and print them in a reverse order.
#include<stdio.h>
main()
{
int ch, count = 0;
char a[100];
printf("Enter Charachters\n");
ch = getchar();
while(ch != EOF && count<100)
{
a[count] = ch;
count = count+1;
ch = getchar();
}
printf("\ncount = %d\n",count);
while (count>0)
{
count = count -1 ;
putchar(a[count]);
}
}
My questinon is:
When we give EOF character (ctrl+D) after typing in a few characters on the console, it does not exit out of the loop. It does not add to the count variable but also does not exit the loop. Only if the EOF character is the first character after a newline character, it is read properly and the loop is exited.
For eg if the sample input is:
abcdef
abc
ctrl+D
Then the code works fine but if the input is:
abcdef ctrl+D
The loop is not exited.
Tell me a way to accomplish this.
Thanks
ctrl-D is actually EOT (End of Transmission). ctrl-Z is EOF (End of File). That isn't specific to unix it is ASCII. unix libraries choose to interpret EOT as a way to signal end of input on character I/O.

Strange phenomenon of console input to a C program [duplicate]

This question already has an answer here:
C input - getchar()
(1 answer)
Closed 9 years ago.
I am runing the following simple program using Visual Studio 2010. The purpose is to see what will happen if I define variable c as char or int, since the getchar() function returns an integer (A widely known pitfall in the C programming language, refer to int c = getchar()?).
#include <stdio.h>
int main()
{
char c;
//int c;
while((c = getchar()) != EOF)
putchar(c);
printf("%d\n",c);
return 0;
}
When I input some characters from the console to this program, I found a strange phenomenon, as shown in the following figure. If the EOF as input follows a sequence of characters (the 1st line), it can not be correctly recognized (a small right arrow is ouput, 2nd line). However, if it is input standalone (4th line), it can be correctly recognized and the program terminates.
I didn't test this program on Linux, but can someone explain why this happen?
What you're describing is, basically, the way terminals are designed.
You need to remember that EOF is not a character. When you type "ABCDEFCTRL-Z", you're entering eight input characters: A, B, C, D, E, F, CTRL-Z, and Return. The only thing special about CTRL-Z (or CTRL-D on Unix/Linux) is that if you type that as the first thing on a new line, then instead of entering a character, the terminal behaves as though the end of the input file has been reached. The getchar() function will return EOF. Since any possible value that can fit into an unsigned char is a valid return value for getchar(), EOF can be distinguished from any valid return value by virtue of being negative, which is why getchar() and family are defined to return int.
If you change your program a little bit and put two printf statements, you will see that the program actually can read the CRTL+Z combination correctly (ASCII code 26):
#include <stdio.h>
int main()
{
char c;
//int c;
while((c = getchar()) != EOF) {
printf("%d\n",c);
putchar(c);
printf("\n");
}
printf("%d\n",c);
return 0;
}
But as the above answer tells, it must be on it's own line; in order to be interpreted correctly. Because on windows, each line has an EOL characters except the last line. There is an EOF character after the last line.

Resources