I'm a beginner and I've recently started learning C and here is an example in "The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie" that I don't understand. This program is supposed to count new lines in input and print out the final result. This is the exact same program that is in the book (page 19). The output of it is nothing. I can input forever and it just goes to a new line...
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
If I put the "printf("%d\n", nl)" statement in the body of the if statement, the output would be printed each time on a new line and the value of "nl" wouldn't reset either. it just increments every time I input something and the program wouldn't terminate.
Why doesn't the example work?
int main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
return 0;
}
I ran it on my computer using Code::Blocks and it worked just fine. maybe you just forgot the int before main and return 0 ^^
I don't understand why the printf() call after the while loop does not get executed?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
I think you are trying to do that
#include<stdio.h>
int main()
{
int characters=0,lines=0;
char ch;
while((ch=getchar())!= EOF)
{
if (ch == '\n')
lines++;
else
{
characters++;
while((ch=getchar())!='\n'&&ch!=EOF); //is to remove \n after a character
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
Output:
a
s
d
f
^Z
lines: 1
Chars: 4
Process returned 0 (0x0) execution time : 8.654 s
Press any key to continue.
Note: ^Z(ctrl+z) is to send EOF to stdin (in windows)
You have to be careful of you're treatment in the while loop. Indeed, you are missing every caracter read in your while statement. You have to save this input, in order to use it afterwards.
The proper syntax would be while(( c = getchar()) != EOF)
You are probably looking for something like this:
#include <stdio.h>
int main()
{
int characters = 0;
int lines = 0;
int c;
while ((c = getchar()) != EOF) {
characters++;
if (c == '\n') {
lines++;
characters--; // ignore \n
}
}
printf("lines: %8d\n", lines);
printf("Chars: %8d", characters);
return 0;
}
while ((c = getchar()) != EOF) might look a bit confusing.
Basically it calls getchar, puts the returned valuee into c ands then checks if c equals EOF.
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
I've been reading "The C Programming Language" and I got to this part of inputs and outputs.
I've read other threads saying that the console doesn't recognize enter as EOF. So that I should use CTRL + Z in Windows or CTRL + D in Unix (neither of those is working for me).
I also read other people asking the same saying they could make it work, the problem in their codes was syntax not the program not terminating.
Is there another solution?
This is the code:
#include <stdio.h>
main()
{
int nb, nl, nt, c;
nb = 0;
nl = 0;
nt = 0;
while ((c = getchar()) != '\n') {
if (c == ' ')
++nb;
else if (c == '\n')
++nl;
else if (c == '\t')
++nt;
}
printf("Input has %d blanks, %d tabs, and %d newlines\n", nb, nt, nl);
}
Edit: The \n was supposed to be an EOF, I was messing around before I posted and I forgot I changed it :P
It doesn't work with EOF neither, I just skipped that one.
while ((c = getchar()) !=EOF) {
}
Then use Ctrl+Z or F6 on Windows
Following will wait for either a \n or EOF, which comes first
while((c = getchar()) != '\n' && c != EOF){
}
On Windows, you type Ctrl-Z on a line by itself (no spaces or anything) and type the Return after that. On Windows, you could technically skip the EOF indicator and keep reading characters, though this doesn't apply to other operating systems because EOF actually means EOF.
while ((c = getchar()) != '\n'){
if (c == ' ')
++nb;
else if (c == '\n')
++nl;
else if (c == '\t')
++nt;
}
According to the condition in your while loop, you will not be able to count number of new lines because you will stop the while loop when the user inputs a new line character ('\n')
Other than that, counting blanks and tabs just works fine.
CTRL+Z will be recognized as a EOF in windows. But in order to recognize it in your program, use condition in while loop as ((c = getchar()) != EOF).
Now when the user presses the key combination: CTRL+Z, It will input to console as EOF, and the program should recognize it as a character input.
Doing this will allow you to count number of lines in the input
So, my suggestion is:
while ((c = getchar()) != EOF){
if (c == ' ')
++nb;
else if (c == '\n')
++nl;
else if (c == '\t')
++nt;
}
If you are on a unix system, the only way to simulate EOF via keyboard while feeding input to the program manually is to press CTRL+D
Here are a couple methods of feeding input to your program and be able to signal EOF at the end of the input:
Make use of the here string format to feed a string representation of a file to the program.
./myprog <<< "Here is a string to work with"
Alternatively, you can also use input redirection to feed a file containing the input to the program.
./myprog < input.file
Any of the above listed methods will work with the following code:
#include <stdio.h>
#ifndef EOF
#define EOF (-1)
#endif
int main(void)
{
int nb, nl, nt, c;
nb = 0;
nl = 0;
nt = 0;
while ((c = getchar()) != EOF){
if (c == ' ')
++nb;
else if (c == '\n')
++nl;
else if (c == '\t')
++nt;
}
printf("Input has %d blanks, %d tabs, and %d newlines\n", nb, nt, nl);
return 0;
}
Not to leave windows out of the game. To simulate EOF on keyboard on windows, use CTRL+Z key combination
Not sure if the here-string format for unix is available for windows, but input redirection should be similar
/* This program will calculate the number of blanks, tabs and new line in a text stream */
#include <stdio.h>
main ()
{
int c,nl = 0, blank = 0, tab = 0; //Newline, blanks and tabs.
while ((c = getchar()) != EOF) {
if (c == '\n')
++nl;
else if (c == '\t')
++tab;
else if (c == ' ')
++blank;
}
printf("Tabs = %d\nBlanks = %d\nNewLine = %d",tab, blank, nl);
}
I wrote this following code and it works properly on Ubuntu. As it is similar to what you wrote, I tried the code and Ctrl-D is working properly in UNIX.
I tested the following code and have realized that if we input \n in text stream it will not increase the counter of the new line, same goes for a \t tab. Only pressing enter for new line and pressing tab for tab is counted by the counter this is a point to be noted.
This is happening because pressing enter actually puts a newline character which is a single character whereas entering \n is treated as differently and they are actually two characters.
I thought this will add value to this question so I explained this thing too.
Thanks.
Change the line
// Buggy, you want calculate the # of '\n' in loop body,
// so logically you shouldn't use it as a stop condition.
while ((c = getchar()) != '\n')
to
while ((c = getchar()) != EOF)
And try press Ctrl + C in your console window on Windows. It works on my platform which is running Win7.
First of all press Ctrl + Z which will print ^Z then press Enter to go to EOF..
I had the same problem, so I check the value of ctrl+D by debugging my code and I found that the value of ctrl+D is 255 and I replaced the EOF with 255, and thats worked for me, if its not working for you try to figure out the value of ctrl + D in Unix.
#include <stdio.h>
main()
{
int nb, nl, nt, c;
nb = 0;
nl = 0;
nt = 0;
while ((c = getchar()) != 255) {
if (c == ' ')
++nb;
else if (c == '\n')
**++nl;**
else if (c == '\t')
++nt;
}
printf("Input has %d blanks, %d tabs, and %d newlines\n", nb, nt, nl);
}
To recognize EOF in Turbo C++, in the terminal window press Ctrl+z; this will act as EOF in the program and then terminate the program....with the condition:
while ((c = getchar()) != EOF)
Im writing a simple program to count the number of character user is entered, and i wrote an if to check wether there is a newline but still printing it..
the code:
#include <stdio.h>
int main()
{
char ch;
int numberOfCharacters = 0;
printf("please enter a word, and ctrl + d to see the resault\n");
while ((ch = getchar()) != EOF)
{
if (numberOfCharacters != '\n')
{
numberOfCharacters++;
}
}
printf("The number of characters is %d", numberOfCharacters);
return 0;
}
what am i doing wrong?
Think about this line:
if (numberOfCharacters != '\n')
how can it make sense? You are comparing the number of characters read so far with a newline, it's like comparing apples to oranges and surely won't work. It's another variable that you should check...
Change your loop to this.
while ((ch = getchar()) != EOF)
{
if(ch != '\n')
numberOfCharacters++;
}