I am trying to catch all characters that I input via my stdin stream except EOF. I want to input a multi-line text: each line with \n at the end.
int getline(char s[])
{
printf("Call-getline()\n");
int c;
int idx=0;
while((c=getchar()) != EOF)
{
s[idx++] = c;
}
printf("\n-EOF found--\n");
s[idx] = '\0';
return idx;
}
I don't know how to get rid of the \n that I get when i press enter, and I was wondering if shif+enter vs enter alone makes any difference. I read about what it does in Microsoft Word: new paragraph vs newline.
The answer Removing trailing newline character from fgets() input was linked in the comments, which show you the solution.
However, I want to point out one other thing here. A common way of ending the input is by pressing Ctrl+D, which will send the EOF to the program. Or at least most (all?) *nix terminals do. But that's a detail specific for the terminal you're using, so you have to read the documentation for your particular terminal.
I found this answer, which tells you about how to do it on Windows. Unfortunately, the answer is basically that you cannot do it in a good way.
If I'm not mistaken, we can press CTRL + C to exit on visual studio and Dev C++ console
otherwise if we talk about CMD then you should write exit followed by an Enter
Related
Following "The C Programming Language" by Kernighan and Ritchie, I am trying to enter the program described on page 18 (see below).
The only changes I made were to add "int" before "main" and "return 0;" before closing the brackets.
When I run the program in Terminal (Mac OS 10.15) I am prompted to enter an input. After I enter the input I am prompted to enter an input again - the "printf" line is apparently never reached and so the number of characters is never displayed.
Can anyone help me with the reason why EOF is never reached letting the while loop exit? I read some other answers suggesting CTRL + D or CTRL + Z, but I thought this shouldn't require extra input. (I was able to get the loop to exit with CTRL + D).
I have also pasted my code and the terminal window below.
#include <stdio.h>
int main(){
long nc;
nc = 0;
while( getchar() != EOF )
++nc;
printf("%ld\n", nc);
return 0;
}
From pg. 18 of "The C Programming Language
My screenshot
You already have the correct answer: when entering data at the terminal, Ctrl-D is the proper way to indicate "I'm done" to the terminal driver so that it sends an EOF condition to your program (Ctrl-Z on Windows). Ctrl-C breaks out of your program early.
If you ran this program with a redirect from an actual file, it would properly count the characters in the file.
EOF means end of file; newlines are not ends of files. You need to press CTRL+D to give the terminal an EOF signal, that's why you're never exiting your while loop.
If you were to give a file as input instead of through the command line, then you would not need to press CTRL+D
Adding to the two good answers I would stress that EOF does not naturally occur in stdin like in other files, a signal from the user must be sent, as you already stated in your question.
Think about it for a second, your input is a number of characters and in the end you press Enter, so the last character present in stdin is a newline character not EOF. For it to work EOF would have to be inputed, and that is precisely what Ctrl+D for Linux/Mac or Ctrl+Z for Windows, do.
As #DavidC.Rankin correctly pointed out EOF can also occur on stdin through bash piping e.g. echo "count this" | ./count or redirecting e.g. ./count < somefile, where somefile would be a text file with the contents you want to pass to stdin.
By the way Ctrl+C just ends the program, whereas Ctrl+D ends the loop and continues the program execution.
For a single line input from the command line you can use something like:
int c = 0;
while((c = getchar()) != EOF && c != '\n'){
++nc;
}
I've written a program which should count upper and lower letters and other signs but it counts anything but when I click Enter and then ^C (EOF). I don't know how to jump over it, hope somebody can help me somehow <3
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
int uppers = 0, lowers = 0, others = 0;
while((ch = getchar()) != EOF)
{
if(islower(ch))
lowers++;
else if(isupper(ch))
uppers++;
else
others++;
}
printf("\n\nUpper letters - %d Lower letters - %d Others- %d", uppers, lowers, others);
return 0;
}
Ctrl+C sends a SIGINT which normally just terminates your application.
What you need is Ctrl+D, which triggers EOF.
EDIT: Note that on Windows' default shell you may need Enter, Ctrl+Z, Enter (or F6) instead (though Ctrl+Z does something else entirely in Linux shells, sending a SIGSTOP). See this question.
You could also compare against 0xD instead of EOF to catch Enter, or maybe use 0x1B which will catch Esc. This way you avoid the weirdness of how to trigger the end-of-input on different platforms (unless you want to process an input stream).
Also take a look at this comment above as well as this answer which contain important additional info that I was missing!
CherryDt has already provided an appropriate answer.
But just to add to that, EOF is not a character but instead an end condition. It may be OS dependent. You can't rely on it to work the same manner in every environment. My suggest would be to use any character itself as a condition to terminate loop, rather than an condition which is environment dependent.
NOTE : The solution worked of ending the program with keys worked for me on Windows only when I included a fflush(stdin); after the getchar(). Probably, getchar() takes the input you give and leaves newline character \n in the input stream which was causing problem when I tried to terminate using ctrl+D or ctrl+Z or F6.
But once you include fflush(stdin), this would solve the problem and now the program ends successfully when I use the F6 on Windows. You can also try with above mentioned keys if this does not work for you.
Hope this helps some Windows users if the above answer wasn't working for them.
So I started to learn C using the ANSI C book. One of the early exercises in the book is to write a program that takes text input and prints every word on a new line, simple enough. So i did:
#include <stdio.h>
#define IN 1
#define OUT 0
main() {
int c;
int state;
state = OUT;
while((c = getchar()) != EOF){
if(c != ' ' && c != '\n' && c != '\t'){
state = IN;
}else if(state == IN){
state = OUT;
putchar('\n');
}
if(state == IN)
putchar(c);
}
getchar();
}
The thing is that while the program works fine it won't break from the while loop if I enter EOF(Ctrl+Z on windows) as the last char of a line or in the middle of it.
So I found an answer here.
What I learned is that the (Ctrl+Z) char is some sort of signal to end the stream and it must be on a new line for getchar() to return EOF. While this is all good and it kinda helped I really want to know why is it necessary for the EOF to be on its own line?
The problem you are having is related to your command line terminal and has nothing to do with the end of file marker itself. Instead of sending characters to the program as you type them, most terminals will wait until you finish a whole line before sending what you type to the program.
You can test this by having the input come from a text file instead of being typed by hand. You should be able to end the input file without a newline without any problems.
./myprogram.exe < input.txt
By the way, the answer you linked to also points out that EOF is not a character that is actually in your input stream, so there is no way for it to come "before" a "\n". EOF is just the value that getchar returns once there are no characters left to be read.
When reading from a tty device (such as stdin for a program running in a console or terminal window) the terminal is in so-called cooked mode. In this mode, some level of line editing facilities are provided, allowing the user to backspace and change what has been typed.
The characters that are typed are not returned to the program until after return has been pressed.
It is possible to do this by placing the terminal in 'raw' mode. Unfortunately it seems this is not well standardised though, so it is somewhat system specific. The answers to this question have some examples for various platforms.
I am reading through "The C Programming Language", and working through all the exercises with CodeBlocks. But I cannot get my character counter to work, despite copying it directly from the book. The code looks like this:
#include <stdio.h>
main(){
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
When I run the program, it opens a window I can type in, but when I hit enter all that happens is it skips down a line and I can keep typing, but I think it's supposed to print the number of characters.
Any idea what's going wrong?
This line:
while (getchar() != EOF)
means that it keeps reading until the end of input — not until the end of a line. (EOF is a special constant meaning "end of file".) You need to end input (probably with Ctrl-D or with Ctrl-Z) to see the total number of characters that were input.
If you want to terminate on EOL (end of line), replace EOF with '\n':
#include <stdio.h>
main(){
long nc;
nc = 0;
while (getchar() != '\n')
++nc;
printf("%ld\n", nc);
}
Enter is not EOF. Depending on your OS, Ctrl-D or Ctrl-Z should act as EOF on standard input.
I ran into the problem tonight, too. Finally found out that Ctrl-D on Linux worked. You build the source file using cc, and start the program and input a word, then press Ctrl-D twice when finished typing. The number that the program countered will be printed just behind the very word you just typed, and the program terminates immediately. Just like this:
The above answer provided by nujabse is correct. But recently coming across this issue myself and researching the answer, I would like to add why.
Using Ctrl+C tells the terminal to send a SIGINT to the current foreground process, which by default translates into terminating the application.
Ctrl+D tells the terminal that it should register a EOF on standard input, which bash interprets as a desire to exit.
What's the difference between ^C and ^D
I'm starting to learn C now and i'm trying to figure out how I would go about capturing when the user hits "enter." I'm looking particularly at the scanf and getc functions but I'm not quite sure how to go about it. When the user hits enter I want to perform some operations while waiting/watching for him to hit enter again... Is "enter" a new line character coming in from the console? Any advice would be much appreciated!
You can check the ascii value using fgetc().
while(condition) {
int c = fgetc(stdin);
if (c==10) {//Enter key is pressed
//your action
}
}
If you just need the input when user presses enter as input you can use scanf or getchar. Here is an example from cplusplus.com
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
This code prints what you entered to stdin (terminal window).
But if you do not want the input ( i know it's really unnecessary and complicated for a new learner) you should use an event handler.
printf("Hit RETURN to exit"\n");
fflush(stdout);
(void)getchar();
Ref: comp.lang.c FAQ list · Question 19.4b
The C language is platform-independent and does not come with any keyboard interaction on its own. As you are writing a console program, it is the console that processes the keyboard input, then passes it to your program as a standard input. The console input/output is usually buffered, so you are not able to react to a single keypress, as the console only sends the input to the program after each line.
However! If you do not demand your console application to be platform-independent, there is a non-standard library <conio.h> in some Windows compilers that has a function called getche();, which does exactly what you want - wait for a single keypress from the console, returning the char that was pressed.