Line Counter In C - c

I am reading a book called C Programming Language 2nd Edition. There it teaches a program called character counting. But according to the output it does not.It just takes the character and does nothing.
This is the first version:
#include <stdio.h>
#include <stdlib.h>
main() {
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '/n')
++nl;
printf("%d\n", nl);
}
So when i type my sentence and press Ctrl+Z to satisfy EOF it gives me zero:
I am a good person
CTRL+Z
0
Press any key to return
It is supposed to count lines and being a beginner I could not understand.

Although the immediate problem is a simple case of replacing '/n' with '\n' (i.e. escaping n for the newline character which is what the backslash does), the fact that your code compiles and runs is due to the C99 standard:
6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or
escape sequence that does not map to a single-byte execution
character, is implementation-defined."
'/n' is a character array consisting of the forward slash and the letter n.
Once you've fixed that, you then will need to make changes to count characters as opposed to just newline characters.

Apparently the implementation is supposed to count only the number of newline characters, not the number of total characters, as implemented in the if(c=='\n') condition. The program returns 0 on your input as it does not contain a newline character.

It looks as if you're missing a set of {} brackets:
#include <stdio.h>
#include <stdlib.h>
main()
{
int c, nl;
nl = 0;
while((c = getchar()) != EOF)
{ // <- This starts the block to be repeated
if (c == '\n')
{ // <- This is just to keep the code 'safe' ...
++nl;
} // <- ... as is this
} // <- This ends the block to be repeated
printf("The number of New Line characters entered was %d\n", nl);
}

might be that the program want to know if the next char is not an end of a line ( '\n') so you'll need:
#include <stdio.h>
#include <stdlib.h>
main() {
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c != '\n')
++nl;
printf("%d\n", nl);
}
this will count the number of characters, but there are others escape characters such as '\t' and so i'm not quite sure what the program is supposed to do, but i think that in your book you'll find some more description clarifying that part
for counting the number of lines simply change '/n' to '\n' as you probably know by now

Related

C Simple Code Involving getchar() and putchar() Unexpected Output

As I was following an example from a book,
#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c)
c = getchar();
}
}
I thought it would make more sense to read character first, then print it so switched putchar and getchar around
c = getchar();
putchar(c);
now when I run it, what happens is the first output of putchar is missing the first character of c? This is the output:
kingvon#KingVon:~/Desktop/C$ ./a.out
first letter is missing?
irst letter is missing?
but now it is not
but now it is not
This is interesting, why does this happen?
Because you're getting a character before the loop. That means c is equal to that first character, but in the loop it's getting every character after that. So,
Get: f
Start the loop
Get: i
Print: i
And so on
The problem is that now you're not printing the character that you read with getchar() before the loop, so you don't print the first character.
If you want to do the getchar() first, put it into the while() condition.
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c)
}
}

Strange 10 value gets printed when I print inputed characters by their ASCII decimal code

#include <stdio.h>
#include <stdlib.h>
int main()
{
int end;
while(( end = getchar() ) != EOF ){
printf("%d\n",end);
}
system("pause");
return 0;
}
I want to print the ASCII codes of characters with this code but whenever I run the code after it gets the char from me it prints its ASCII equivalent with decimal 10. For example if I run the code and pass "a", it will print 97 and 10. Why does it print 10, this happens with all other characters too.
Thank you for answers and as a followup question when I add a counter after I input a character counter's value increases by two, why does this happen
#include <stdio.h>
#include <stdlib.h>
int main()
{
int end;
int count=0;
while(( end = getchar() ) != EOF ){
printf("%d\n",end);
count++;
printf("counter is now %d\n",count);
}
system("pause");
return 0;
}
As stated you are printing the ASCII decimal codes for 'a' and '\n' respectively, this is because, in your code, getchar reads all the characters in the stdin buffer, including the newline character which is present because you press Enter.
You can avoid this by simply making it be ignored by your condition:
while((end = getchar()) != EOF && end != '\n'){
printf("%d\n", end);
}
Disclaimer: David Ranieri added a comment with the exact same solution as I was writing my answer (which he kindly deleted) so credit to him as well.
Regarding your comment question and the question edit:
If you don't want the '\n' to interrupt your parsing cycle, you can simply place the condition inside it.
while((end = getchar()) != EOF){
if(end != '\n'){ //now as '\n' is ignored, the counter increases by one
printf("%d\n", end);
count++;
printf("counter is now %d\n",count);
}
}
The reason why the counter is increased by two is, again, because two characters are parsed, whatever character you input and the newline character. As you can see in the sample, if you ignore the '\n', the counter will only increase by one, provided that you only enter one character at a time.
In ASCII, a newline is represented by the value 10.
Anytime you type a sequence of characters and press the ENTER key, you get the ASCII values for the letters/numbers/symbols you types as well as the value 10 for the newline.

getchar/putchar returns boxes with question marks when printing inputted characters

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...

How to read a stream of characters whose length is unknown from standard input in c

I want to read a stream of characters from standard input whose length is unknown. I am trying to read character by character as
#include <stdio.h>
int main(void)
{
char ch;
do
{
scanf("%c",&ch);
//do some comparison of ch
}while(ch!='');
return 0;
}
Help me write the condition in while so that I can read input properly without entering into an infinite loop
Sample input:
abcdefghijklmnop
Probably a simplest form of solution will be this
#include <stdio.h>
int main(void)
{
char ch;
do
{
ch = fgetc(stdin);
//do some comparison of ch
}while( ch != EOF );
return 0;
}
But having said that, problem statement like below
read a stream of characters from standard input whose length is
unknown
is a bit tricky. As per the program above is concerned you can probably stop it with a ctrl+d, EOF or run the binary with file redirection
./a.out < input.txt
in fact, the interpretation of standard input is what makes this question more meaningful.
Your escape character is wrong.
Your want to write everything on one line ? Then use '\n' to end your loop.
while (ch != '\n')
If you write character by character, use one to exit your sequence (for exemple '#')
while (ch != '#')

Working of getchar and putchar or example in The C language 2nd Edition

CODE 1:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
CODE 2:
#include<stdio.h>
main( )
{
int c,d;
c=getchar();
d=getchar();
putchar(c);
putchar(d);
}
1) If
Input : bo
Output : bo
I got to know this in 2nd program that it stores both in variables c and d but where does it stores them in 1st program.
2)Pl. explain the working of first program why it repeats any word despite of its length that is more than one character.
3) From book i got to know that EOF is encountered whenever I enter or there is some error but even if I press enter this program doesn't stops but it prints nextline character again.
For question one, it stores them in c (but only one at a time). The code, better indented, is:
while ((c = getchar()) != EOF)
putchar(c);
so you can see that, for each character input into c, it outputs it as well. Keep in mind that syntax is the short form for:
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
so you can see each iteration of the loop gets the next character.
The second question, I assume you're asking why it works for any length input. That's because it doesn't care about the length. It's simply storing and echoing each individual character.
You could give it a billion characters if you like.
As to the third, you get back EOF for an error or end of file (CTRL-Z at the start of a line for Windows, usually CTRL-D under UNIX-like operating systems, unless you have some weird terminal characteristics set up).
If you were only interested in a line, you could use something like:
while ((c = getchar()) != '\n')
putchar(c);
putchar ('\n');
while ((c = getchar()) != EOF)
Reads the value from stdin until it encounters EOF(End Of File). So the same variable c stores different values read in different iterations.
In the second example only two variable ( of char type ) are there so it can read and store only two characters.

Resources