This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why doesn’t getchar() recognise return as EOF in windows console?
I'm trying to print out the value in the variable 'nc' in the next program:
int main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
Please tell me why is it not printing?
You don't have brackets in your while loop (this is why not using brackets leads to error prone software). Therefore, the value is getting incremented, but not printing.
Try:
int main(int argc, char** argv)
{
long nc;
nc = 0;
while (getchar() != EOF)
{ // ADD THIS
++nc;
printf("%ld\n", nc);
} // AND THIS
}
otherwise, your code is essentially doing:
int main(int argc, char** argv)
{
long nc;
nc = 0;
while (getchar() != EOF)
{
++nc; // ENDLESSLY ADDING
}
printf("%ld\n", nc); // NEVER REACHED DUE TO WHILE LOOP.
}
Your while loop will continue to loop until you end the input using Control-D on Unix or Control-Z, Return on Windows. It will do this without printing anything because you did not use braces around the ++nc and printf.
You may also have problems with printf if you did not #include <stdio.h> at the top of your program. If the compiler does not know that printf is a varargs function, it will not format the argument list correctly when calling it.
after entering some inputs like
1
2 4
u must type ctrl + D since its the EOF ASCII equivalent.
Else modify the progeam and put
while(getchar()!='\r') (until you hit Enter)
What do you mean? It works:
./a.out
asdfsdfasdfasdfasddddddddddddddddddddddd
41
echo "Try to count this" | ./a.out
18
you have to stop reading characters from stdin by stopping the while loop of getchar
and then you will see the nc value printed
To do
EOF = CTRL + D (for Linux)
EOF = CTRL + Z (for Windows)
Related
I am new to C (self-learning).
When I execute this for-loop function when I type 'hello' the output will be 012345. However it skips to last print function outside of the for-loop?
int main() {
int c;
for (c = 0; getchar() != EOF; ++c) {
printf("%d\n", c);
}
printf("%d\n", c);
return 0;
}
The output:
hello
0
1
2
3
4
5
"When I execute this for-loop function and I type 'hello' the output will be 012345".
What do you expect else? c just get incremented by each iteration, starting at 0.
"However it skips to the last print function outside of the for-loop?"
No, it doesn´t. In fact, It isn´t even out of the for loop. The newline made by the press to Enter doesn´t let you break out of the loop; only a signalized EOF is doing that.
So, the program isn´t even terminated. It stucks in the loop.
You need to signalize EOF with CTRL + D on Linux or CTRL + Z on Windows to break out of the loop.
No it is not skipping anything.
Note: you are printing c which is integer (not character, if that is what you want). So, input "hello" has 5 characters: so, output is:
0
1
2
3
4
Then, as there is newline character '\n' as you pressed enter (there is your output 5). However, you loop never exits, unless you force program to do so (I mean, interrupting with Ctrl +C). If you, test again your code, and input data even after "hello", you will see that, you are still in the loop.
Change your program to this:
#include <stdio.h>
int main() {
int c;
int ch;
for (c = 0; (ch = getchar()) != EOF; ++c) {
printf("%d %d\n", c, ch);
}
printf("%d %d\n", c, ch);
return 0;
}
Now you should understand yourself what happens.
The while loop doesn't end when you type hello and presses Enter, because getchar() still won't be equal to EOF. So the loop will continue with getchar() waiting to read new characters.
You need to press Ctrl+Z on Windows' cmd.exe, or Ctrl+D on Linux's terminal, to proceed with the execution of the program without writing any character to the input, then getchar will fail to read a character and return EOF, finally exiting the loop. Once it is out of the loop the final printf call will be made before ending the program.
Alternatively you could change the condition to make the loop end when getchar reads a new line character \n, instead of when it fails to read a character, so that the loop will end after you press Enter:
int main() {
int c;
for (c = 0; getchar() != '\n'; ++c) {
printf("%d\n", c);
}
printf("%d\n", c);
return 0;
}
I see what you're tryng to do, but first of all i'd declare "c" as a char , this way you're doing an implicit cast to char, which is allowed in C language, but should be avoided.
My best guess would be that you'r compiler (i suppose mingw on windows) is not telling you what's going on exactly, try this:
When you build (compile) something outside linux for C language do as follows :
" gcc -o nameoftheexecutable file.c -Wall " and to execute it " ./nameoftheexecutable
That -Wall will print out all warnings to the console, including EOF warnings.
By doing this, and understanding what IDE or Environment are you programming in, we can help you out.
This question already has answers here:
Difference between int and char in getchar/fgetc and putchar/fputc?
(2 answers)
Closed 3 years ago.
I'm reading through the K&R book and implemented the 'copy' example:
#include <stdio.h>
int main() {
char c;
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
All normal input appears to work correctly but when an EOF (^D) is entered the program prints infinite "�" characters and I must halt the program manually.
I have tried using putchar(c); as well as printf("%c", c); to the same effect.
Does anyone know the cause of this?
Since c is of type char, an int value returned from getchar will be converted to the type char before it is compared to EOF.
Since the EOF is an in-band error mechanism, it has to be an error value that can be distinguished from all valid characters that could be returned. When you assign EOF to a char you discard information.
After executing:
char c = EOF;
the statement
c == EOF
is false.
Preserve the return type of getchar by doing:
int c;
instead of:
char c;
Using int c instead of char c should solve your issue
Playing around with code examples from K&R in Codeblocks on Windows 10 (Danish language). The following example works as expected:
#include <stdio.h>
int main() {
char c = 'a';
putchar(c);
}
However, the following prints a series of boxes with question marks, the same number as the number of characters I type:
#include <stdio.h>
int main() {
char c;
while (c = getchar() != '\n') {
putchar(c);
}
}
So it looks like an encoding issue. When run, a command prompt opens with "C:\Users\username\Desktop\filename.exe" in the header, and my username contains the Danish character "å" which is replaced by a "Õ". The command prompt uses the CP 850 character set.
(By the way, I'm not checking if the character equals EOF, since that produces odd results. Pressing enter prints the expected number of boxes, plus one for \n, but it doesn't end the program.)
You are seeing a problem of operator precedence here. As you can see on this chart, = has a lower precedence than !=.
This means that getchar() != '\n' is evaluated first.
To the compiler your code looks like this:
#include <stdio.h>
int main() {
char c;
while (c = (getchar() != '\n')) {
putchar(c);
}
}
Since 'c' is getting an incorrect value (the true/false evaluation of the expression), the output is incorrect, and the program gives the behavior you are seeing, however
#include <stdio.h>
int main() {
char c;
while ((c = getchar()) != '\n') { //<----notice brackets around c=getchar
putchar(c);
}
}
gives the output you are expecting. This illustrates the fact that you should always put brackets around such expressions to be safe.
This line is bad.
while (c = getchar() != '\n')
It should be:
while ((c = getchar()) != '\n')
There are already some correct answers within the scope of the question but there are a couple of wider problems that you need to address.
Firstly getchar() returns an int and it is important that you define the variable that takes the return value as an int so you can differentiate errors and end of file from valid chars.
Secondly, if you receive end of file or there is an error on stdin before the program encounters a \n, your code will loop forever. This is what the man page on my laptop says about getchar()
If successful, these routines return the next requested object from the stream. Character values are returned as an unsigned char converted to an int. If the stream is at end-of-file or a read error occurs, the routines return EOF.
So once getchar() returns EOF it will return EOF all the time. You need to address this in your loop condition:
#include <stdio.h>
int main()
{
int c; // c declared as int
while ((c = getchar()) != EOF && c != '\n'))
{
putchar(c);
}
if (c == EOF)
{
// handle errors and end of file as you see fit
}
}
Edit: You get the boxes because of the lack of parenthesis around the assignment, look at this question for reference as to why you should have parenthesis around an assignment used as a truth value...
Also, there is something else that is also wrong with this program, consider this example:-
For example:
What you actually wanted:-
ABCD
< newline >
What you actually typed:-
ABCD
And since the program didn't find the '\n' anywhere in the code, it leads to undefined behavior since it goes out of bounds to find it...
There are two possible solutions when your input does not contain a '\n':-
Use EOF (Suggested by many since it the best possible solution for accepting every input...)
int main() {
char c;
while ((c = getchar()) != '\n') /* Always remember to put parenthesis around
an assignment in a condition... */
putchar(c);
}
Add a newline to your input:-
int main() {
char c;
// Use fputc to modify input...
fputc('\n', stdin);
while ((c = getchar()) != '\n') /* Always remember to put parenthesis around
an assignment in a condition... */
putchar(c);
}
But, beware! This method will stop at the first iteration of newline it gets, so if you have something outside of the '\n', well it won't be printed...
This question already has answers here:
For vs. while in C programming?
(19 answers)
Closed 4 years ago.
The goal is to write a simple character counting program in C. If written like this:
#include <stdio.h>
main()
{
long nc;
for(nc = 0; getchar() != EOF; ++nc)
printf("%ld\n", nc);
}
the last number listed in its output will be the correct number of characters. However, if written like this:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF)
{
++nc;
printf("%ld\n", nc);
}
}
the last number in its output will always be larger by one than the true number of characters in the input string. I learned that this is because pressing Enter after inputting the desired string introduces a newline character which gets counted and produces the error. To eliminate that error is trivial, but my question is why doesn't the same problem occur in the program written above?
For example, the first program will correctly output 0 if ran without input. The second one however will output 1 in the same scenario. Why the difference?
All numbers are larger by one in the second loop, not just the last.
Your for-loop is equivalent to
nc = 0;
while (getchar() != EOF)
{
printf("%ld\n", nc);
++nc;
}
As you can see, it increments after printing, and your while increments before printing.
The difference is due to the order in which the statements are executed in both the scenario.
In case of for loop, the order is:
(1) (2) (4)
|----| |---------------| |
for(nc = 0; getchar() != EOF; ++nc)
printf("%ld\n", nc); --------------- (3)
and in case of while loop, the order is:
nc = 0; ------------------- (1)
while(getchar() != EOF) --------------- (2)
{
++nc; -------------------- (3)
printf("%ld\n", nc); ------------ (4)
}
So, in case of for loop the ++nc is last executed in every iteration i.e. after printf() and in case of while loop the ++nc is executed before the printf() in every iteration. Hence, you are observing the difference.
I wrote a simple c program to count number of characters
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
This program is not printing me the characters. On testing different cases, I found that I am stuck in an infinite while() loop.
This program isn't printing me the characters
It won't. You did not add any statement to print them.
I found that i'm stuck in an infinite while loop
If you don't hit the breaking condition, you'll be in the loop. You need to get EOF to exit the loop. use
CTRL+Z (on windows)
CTRL+D (on linux)
Now, the solutions:
getchar() won't print the values. You have to store the values and print explicitly (if you want to) using , maybe putchar().
You either supply EOF or change the breaking condition of while() to come out of the essential infinite loop otherwise.
Apart from the coding issues, you need to think about the logic, too. In the present form of the code, getchar() counts the newline (\n) as a valid character, too. To explain, an input in the form of
$ ./a.out ENTER
a ENTER
s ENTER
d ENTER
f ENTER
g ENTER
CTRL+D
Will produce a result
10
but that is not what we generally call counting the character. You may want to review this part of the logic, too.
That said, the recommended signature of main() is int main(void).
Try the following
#include <stdio.h>
int main( void )
{
int c;
long nc = 0;
while ( ( c = getchar() ) != EOF && c != '\n' ) ++nc;
printf( "%ld\n", nc );
}
You have to generate the EOF state ( Ctrl+d in UNIX-systems or CTRL+z in Windows) or simply press Enter.
Try like this:
#include <stdio.h>
int main(void)
{
int c;
long nc = 0;
while ( ( c = getchar() ) != EOF && c != '\n' )
++nc;
printf( "%ld\n", nc );
}
while (getchar() != '\n')
++nc;
printf("%ld \n",nc);
Worked!