Exercise 1-6: (page 17 K&R) - getchar() question - c

When I run the program below, output give second 1. I debug the program, but I couldn't understand why compiler writing second 1 anytime?
output like this.
#include <stdio.h>
main()
{
int c;
while (c = getchar() != EOF)
printf("%d\n", c);
printf("%d - at EOF\n", c);
}

The condition in the while statement
while (c = getchar() != EOF)
is equivalent to
while (c = ( getchar() != EOF) )
due to the operator precedence. And this logical expression getchar() != EOF always yields 1 if the input was not interrupted.
You need to write
while ( ( c = getchar() ) != EOF)

The Enter key you press to "send" the input from the terminal to the program is added in the input buffer as a newline '\n', which will be read in the second iteration of the loop.

Related

Simple C code contains ((c = getchar()) != EOF)

I run the following simple C code.
int main()
{
int c;
while ((c = getchar()) != EOF)
{
putchar(c);
printf("%d\n", c);
}
return 0;
}
The output of code when I enter character A as input from keyboard is as follow:
>A
>A65
>
>10
>
Why does this code print the number 10 after each inner while loop?
Think about what you're doing when the program is asking for input.
Are you just hitting A?
No, you're hitting AEnter, and hitting the Enter key results in a newline, so your while loop is actually doing this:
1. Enter loop
2. getchar() waits for input from stdin
2. You enter 'A', hit 'Enter'
3. c is assigned '65' (integral value of 'A')
4. putchar(c) and then printf("%d\n"), so you see 'A65'
5. getchar() immediately gets next character from stdin, which is linefeed
6. c is assigned '10' (integral value of '\n')
7. putchar(c) and printf("%d\n"), so you see a newline followed by 10.
You can make your code ignore the linefeeds/non-printable characters if you want (this depends on your locale), using isprint:
#include <stdio.h>
#include <ctype.h>
int main() {
for(int c; (c = getchar()) != EOF;) {
if (!isprint(c)) {
printf("Ignoring character with value %d\n", c);
} else {
putchar(c);
printf("%d\n", c);
}
}
return 0;
}
And if I run this:
root#6f67da78fe9a:~# gcc -o chartest source.c
root#6f67da78fe9a:~# ./chartest
A
A65
Ignoring character with value 10

No output when in run Line counting

When i run the line counting code in the C programming language book, i do not get any output.ie nothing is returned that reflects the number of lines. The code is below:
#include <iostream>
//This program counts lines in its input
//
int main() {
int c, nl;
nl = 0;
while ((c = getchar())!= EOF )
if (c == '\n')
++nl; //nl = nl +1
printf("%d\n", nl);
}
The output is below:
/home/xxx/xxxx/lineCounting1/cmake-build-debug/lineCounting1
line1
line2
line3
line4
^D
Process finished with exit code 0
I use ctrl+D to stop the execution and get an output. But nothing (except ^D is returned). What am i doing wrong?
this is a C program so we have to include stdio.h instead of iostream.
in the main we have declared 2 variables
data type of variable name "c" should be "char" and nl is a counter which is currently set to 0.
getchar() is a library function which takes only the first character of of the string.
we are assigning the value of getchar to the c. and traversing it till end of file (EOF).
if condition is true then we are entering into the while.
there is a if condition inside the while which states that if(c == '\n') then incrementing the counter (nl) and displays the count.
code will be look like this but still it won't work because it is entering into the infinite loop
we have to assign something to the variable c.
`#include<stdio.h>
//This program counts lines in its input
int main()
{
char c;
int nl;
nl = 0;
printf("Enter the character\n");
while((c = getchar())!= EOF )
{
if (c == '\n')
{
++nl; //nl = nl +1
printf("%d\n", nl);
}
}
}`

c = getchar() != EOF; prints 0 or 1

When i run this code it prints the dos 0 character(space) once, puts a space and prints dos 1 character(smiley face with white eyes and mouth).
int c = 0, b = 1;
printf("%c %c", c, b);
But when i run this code below the result is being printed twice. I either get 2 spaces or 2 smiley faces.
while(c != -1)
{
c = getchar() != EOF;
putchar(c);
}
Edit: My code doesnt have paranthesis so it compares every single entered character with EOF and assigns the result (0 or 1) to c and then prints c as a char. In order to prevent this, we can use paranthesis to force the program to do c = getchar() first and then compare that value with EOF.
while((c = getchar()) != EOF)
Your problem is that a '\n' character is not equal to EOF. The '\n' is being read in as a second character.

Counting input characters in C

I have just started learning C, been reading a C textbook by Keringhan and Ritchie. There was this example in the textbook, counting characters from user input. Here's the code:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF) {
if (getchar() != 'q')
++nc;
else
break;
}
printf("%ld\n", nc);
}
The problem is, when I execute the code, if I input only one character per line, when I input "q" to break, it doesn't do so. I have to type some word per line, only after that it will break the loop. Also, it only counts the half of the characters of the word. I.e. if I input
a
b
russia
it will only print '5' as final result.
Could you please explain to me why is this happening?
This works, but only when you finish off with an Enter. So, this will count the characters until the first "q" appears. That is just how getchar() and getc(stdin) work.
#include <stdio.h>
int main() {
char c = 0;
long count = 0;
short int count_linebreak = 1; // or 0
while((c = getchar()) != EOF) {
if(c != 'q' && (count_linebreak || (!count_linebreak && c != '\n'))) {
++count;
}else if(c == 'q') {
printf("Quit\n");
break;
}
}
printf("Count: %ld\n",count);
return 0;
}
A StackOverflow question about reading stdin before enter
C read stdin buffer before it is submit

why does getchar in while not execute after first iteration? [duplicate]

This question already has answers here:
`getchar()` gives the same output as the input string
(5 answers)
Closed 9 years ago.
I wrote a program to read from input character by character and print it to output and here is my code:
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF)
{
printf("%s\n", "log1");
printf("%c\n", c);
printf("%s\n", "log2");
}
}
and this is the result:
a(my input)
log1
a
log2
log1
log2
but it should have this result:
a
log1
a
log2
what's wrong with this program?
you giving input a and newline
a(my input) You are giving a and newline
//this is because of a
log1
a
log2
//this is because of newline
log1
log2
Check for newline and avoid printing Newline.
while((c = getchar()) != EOF)
{
if(c!='\n')
{
printf("%s\n", "log1");
printf("%c\n", c);
printf("%s\n", "log2");
}
}
This is because you while((c = getchar()) != EOF) ends after hitting EOF. This is because when you type something and you hit the enter key then everything is stored in an internal buffer.
Your code stops when getchar doesn't find anything in that buffer.
You may also check out this:- Where does getchar() store the user input?
getchar is running during the second iteration. The problem is that your input was actually "a[enter]", so the second character that getchar read was a newline character, and it printed that.
If you give input of "abc", the things may seem more clear.
while(getchar() != '\n');
bear in mind that the expression in the while loop is executed everytime - so even when the character is '\n' is found, it has already been removed from the stream by the getchar() call.
Place a condition not to print \n (on pressing Enter
while((c = getchar()) != EOF)
{
if(c != '\n')
printf("%s\n", "log1");
printf("%c\n", c);
printf("%s\n", "log2");
}

Resources