Begginer C Question About getchar()
As a preface, I have done my best to read through the FAQs on this forum so if I am violating the forum rules it's not out of negligence.
That said, I have a question regarding how the getchar() function in the stdio library works. For contextual purposes, I am writing a simple program that takes input from the terminal (stdin) and stores the inputted characters into a consolidated C string.
In short, my question is what exactly happens when the user presses the Enter key? I am wondering if the reaction is relative to the OS, or if there is some standard signal that is sent when this key is pressed. I am aware that the newline character, '\n', is appended to the end of the current string of characters, but why does it also cause the program to start executing the getchar() function inside of the for loop?
1 #include <stdio.h>
3 #define MAX_LENGTH 10
5 int readbuff(char);
9 char buff[MAX_LENGTH];
12 printf("%s", buff);
14 return 0;
17 /* read buffer and return the number of characters input */
18 int readbuff(char buff)
20 int c, i;
22 for(i = 0; i < MAX_LENGTH - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
23 buff[i] = c;
24 if(c == '\n')
25 buff[i++] = c;
26 buff[i++] = '\0';
28 return i;
I am running Ubuntu 11.04 with the BASH if that makes a difference.