This question already has answers here:
Cannot figure out how to use getchar(); in C
(4 answers)
Closed 8 years ago.
I read few questions on Stack Overflow but everyone here is explaining that has already been explained in K&R. I want to ask when the below program runs. Then if I input my name in the console then it get printed in the next line. Firstly this function's name is getchar why it doesn't take just one character 'a' or any other? I get correct output irrespective of how long my input is.
I wrote 'adfsajfsjssadfsa.......up to to 100 characters and putchar copied it exactly'. Also book is using int. I know int can hold data up to 4 bytes much bigger than char but what's the use of providing data types in C if we can use any of them.
Why does putchar print it to next line? Is it built this way to always print the output in next line? I wrote adfsajfsjssadfsa.......upto to 100 characters and putchar copied it exactly when will a situation come that I would get error and integer c won't be able to hold that big data. How many characters?
#include <stdio.h>
int main()
{
int c;
c=getchar();
while(c!=EOF){
putchar(c);
c=getchar();
}
}
You are calling getchar and putchar multiple times (because they are inside a loop) so they get and print multiple characters.
You MUST use an int variable when using getchar, because getchar can return any character or EOF. EOF isn't a character, so it doesn't fit in a char, and it represents the end of the file.
Variable c will always contain just 1 character, which is int. You are overwriting previous value with return value of a function getchar in each iteration of a loop.
Also try to avoid duplicate code by rewriting the while loop. You can call function getchar and assign value to variable c inside the while condition:
while ((c = getchar()) != EOF) {
putchar(c);
}
Related
This question already has answers here:
Why does this code print lines and not single chars
(3 answers)
Canonical vs. non-canonical terminal input
(1 answer)
Closed last year.
Working my way through K&R and having a hard time understanding the behavior of getchar.
Consider the following code
#include <stdio.h>
void main()
{
int c;
while (( c = getchar()) != EOF)
{
putchar(c);
}
}
I would expect this program to output each character as I type it, but instead the loop only executes after a newline has been entered. Does getchar not return until a newline is entered?
Thank you in advance for any explanation
Just started on K&R and hit:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
And it just displays what I input, even if it's a string of text.
cacti
cacti
stop repeating what i'm saying
stop repeating what i'm saying
Just like that.
What I don't get is why I can't just instantiate variable c with a string of text and print it the same way. (Ignoring the while loop for the sake the example) Like with:
main()
{
int c;
c = "cacti";
putchar(c);
}
Wherein the output is apparently just 'd'
Here c is only integer which take a character for your case(Although its limits are larger than that).
For first code segment:
getchar() only return a character and you use while loop which take a character from stream and through putchar() it print to console until end of file. You seems to get a line of string and print it but it don't do that way.
In second code segment:
You put a const char* to integer which is not valid(My gcc 4.9.2 does not compile). So it show undefined character (Why print 'd' I don't know, may be compiler issue).
You can do this by:
main()
{
char c[] = "cacti";
puts(c);
}
EDIT
According to getchar() definition:
On success, the character read is returned (promoted to an int value).
The return type is int to accommodate for the special value EOF, which indicates failure.
When you type a single line and press enter then first character read outside of while loop. Than check if it is EOF(End Of File- No more data on the file . You can give EOF by pressing Ctrl+Z in windows and Ctrl+D in linux).
As if it is not encountered EOF, then it entered in while loop and print the singe character(by putchar(c)). After the next line c=getchar() take another character you entered in previous line and check while loop condition while(c!=EOF) being true it entered into loop and print a character. It continues until there found any character to print.
So it makes confuse with puts() which Writes a string in standard output.
Where putchar() Writes a character to the standard output.
According to http://www.cplusplus.com/
Writes the C string pointed by str to the standard output (stdout) and appends a newline character ('\n').
You could use a line-oriented input function to read whole lines. For example:
#include <stdio.h>
int main(void)
{
char line[4096];
while (fgets(line, sizeof(line), stdin) != 0)
fputs(line, stdout);
return 0;
}
For most plausible files, this will read one line at a time into the array of characters, and then write that line out. (If the line length is longer than 4095 characters, then lines will be processed in multiple segments.) If the file contains null bytes, then the material from the null byte to the end of line will be ignored. There are fixes for that — see standard C functions fread() and fwrite(), and POSIX function
getline().
Note that your second example:
int main(void)
{
int c;
c = "cacti";
putchar(c);
}
shouldn't compile without warnings about assigning a character pointer to an integer. When you use putchar() on the result, it probably prints the least significant byte of the address where the string "cacti" is stored. It is pure coincidence that the character printed is d.
The putchar() function only ever prints a single byte (which means a single character in many code sets, but it might only be part of a character in UTF-8).
This question already has answers here:
Why doesn't getchar() recognise return as EOF on the console?
(8 answers)
Closed 8 years ago.
I am a complete beginner in C, so sorry if this question sounds too trivial.
My understanding of getchar() and putchar() is that they process text streams one character at a time. Let's say I have this program that takes textual input from the user and displays it on the screen:
#include <stdio.h>
main(){
int c;
c = getchar();
while(c!= EOF){
putchar(c);
c=getchar();
}
}
Here's what I think is happening:
Suppose I run this program and I enter the word Hi. getchar reads the first character (namely H) and stores it in c. Then the program enters the while loop and puts H to the screen. Then it gets the next character (i) and prints it. Then comes the EOF and when getchar assigns the value to c, the while loop ends. So, according to this interpretation of what has happened, the program should end after printing all the characters and having reached the end of file.
When I run the program, however, after printing the string, the program waits to receive additional input, meaning it doesn't end, rather waits for the user to input more text streams.
Why does this happen and where do I get it wrong?
When you typed Hi and ENTER, no EOF is automatically inserted.
Instead, you need to press certain keys to generate EOF. On Unix system, press Ctrl + D, on Windows, press Ctrl + Z.
This question already has an answer here:
C input - getchar()
(1 answer)
Closed 9 years ago.
I am runing the following simple program using Visual Studio 2010. The purpose is to see what will happen if I define variable c as char or int, since the getchar() function returns an integer (A widely known pitfall in the C programming language, refer to int c = getchar()?).
#include <stdio.h>
int main()
{
char c;
//int c;
while((c = getchar()) != EOF)
putchar(c);
printf("%d\n",c);
return 0;
}
When I input some characters from the console to this program, I found a strange phenomenon, as shown in the following figure. If the EOF as input follows a sequence of characters (the 1st line), it can not be correctly recognized (a small right arrow is ouput, 2nd line). However, if it is input standalone (4th line), it can be correctly recognized and the program terminates.
I didn't test this program on Linux, but can someone explain why this happen?
What you're describing is, basically, the way terminals are designed.
You need to remember that EOF is not a character. When you type "ABCDEFCTRL-Z", you're entering eight input characters: A, B, C, D, E, F, CTRL-Z, and Return. The only thing special about CTRL-Z (or CTRL-D on Unix/Linux) is that if you type that as the first thing on a new line, then instead of entering a character, the terminal behaves as though the end of the input file has been reached. The getchar() function will return EOF. Since any possible value that can fit into an unsigned char is a valid return value for getchar(), EOF can be distinguished from any valid return value by virtue of being negative, which is why getchar() and family are defined to return int.
If you change your program a little bit and put two printf statements, you will see that the program actually can read the CRTL+Z combination correctly (ASCII code 26):
#include <stdio.h>
int main()
{
char c;
//int c;
while((c = getchar()) != EOF) {
printf("%d\n",c);
putchar(c);
printf("\n");
}
printf("%d\n",c);
return 0;
}
But as the above answer tells, it must be on it's own line; in order to be interpreted correctly. Because on windows, each line has an EOL characters except the last line. There is an EOF character after the last line.
I've started reading "The C Programming Language" (K&R) and I have a doubt about the getchar() function.
For example this code:
#include <stdio.h>
main()
{
int c;
c = getchar();
putchar(c);
printf("\n");
}
Typing toomanychars + CTRL+D (EOF) prints just t. I think that's expected since it's the first character introduced.
But then this other piece of code:
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF)
putchar(c);
}
Typing toomanychars + CTRL+D (EOF) prints toomanychars.
My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored?
EDIT:
Thanks to everyone for the answers, I start to get it now... only one catch:
The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?
getchar gets a single character from the standard input, which in this case is the keyboard buffer.
In the second example, the getchar function is in a while loop which continues until it encounters a EOF, so it will keep looping and retrieve a character (and print the character to screen) until the input becomes empty.
Successive calls to getchar will get successive characters which are coming from the input.
Oh, and don't feel bad for asking this question -- I was puzzled when I first encountered this issue as well.
It's treating the input stream like a file. It is as if you opened a file containing the text "toomanychars" and read or outputted it one character at a time.
In the first example, in the absence of a while loop, it's like you opened a file and read the first character, and then outputted it. However the second example will continue to read characters until it gets an end of file signal (ctrl+D in your case) just like if it were reading from a file on disk.
In reply to your updated question, what operating system are you using? I ran it on my Windows XP laptop and it worked fine. If I hit enter, it would print out what I had so far, make a new line, and then continue. (The getchar() function doesn't return until you press enter, which is when there is nothing in the input buffer when it's called). When I press CTRL+Z (EOF in Windows), the program terminates. Note that in Windows, the EOF must be on a line of its own to count as an EOF in the command prompt. I don't know if this behavior is mimicked in Linux, or whatever system you may be running.
Something here is buffered. e.g. the stdout FILE* which putchar writes to might be line.buffered. When the program ends(or encounters a newline) such a FILE* will be fflush()'ed and you'll see the output.
In some cases the actual terminal you're viewing might buffer the output until a newline, or until the terminal itself is instructed to flush it's buffer, which might be the case when the current foreground program exits sincei it wants to present a new prompt.
Now, what's likely to be the actual case here, is that's it's the input that is buffered(in addition to the output :-) ) When you press the keys it'll appear on your terminal window. However the terminal won't send those characters to your application, it will buffer it until you instruct it to be the end-of-input with Ctrl+D, and possibly a newline as well.
Here's another version to play around and ponder about:
int main() {
int c;
while((c = getchar()) != EOF) {
if(c != '\n')
putchar(c);
}
return 0;
}
Try feeding your program a sentence, and hit Enter. And do the same if you comment out
if(c != '\n') Maybe you can determine if your input, output or both are buffered in some way.
THis becomes more interesting if you run the above like:
./mytest | ./mytest
(As sidecomment, note that CTRD+D isn't a character, nor is it EOF. But on some systems it'll result closing the input stream which again will raise EOF to anyone attempting to read from the stream.)
Your first program only reads one character, prints it out, and exits. Your second program has a loop. It keeps reading characters one at a time and printing them out until it reads an EOF character. Only one character is stored at any given time.
You're only using the variable c to contain each character one at a time.
Once you've displayed the first char (t) using putchar(c), you forget about the value of c by assigning the next character (o) to the variable c, replacing the previous value (t).
the code is functionally equivalent to
main(){
int c;
c = getchar();
while(c != EOF) {
putchar(c);
c = getchar();
}
}
you might find this version easier to understand. the only reason to put the assignment in the conditional is to avoid having to type 'c=getchar()' twice.
For your updated question, in the first example, only one character is read. It never reaches the EOF. The program terminates because there is nothing for it to do after completing the printf instruction. It just reads one character. Prints it. Puts in a newline. And then terminates as it has nothing more to do. It doesn't read more than one character.
Whereas, in the second code, the getchar and putchar are present inside a while loop. In this, the program keeps on reading characters one by one (as it is made to do so by the loop) until reaches reaches the EOF character (^D). At that point, it matches c!=EOF and since the conditions is not satisfied, it comes out of the loop. Now there are no more statements to execute. So the program terminates at this point.
Hope this helps.