Reputation: 61
example code is (comments are what I imagine it's doing for the first loop):
#include <stdio.h>
#define BACKSPACE 8
main()
{
int c;
while((c = getchar()) != EOF) //output: GODDAMN NOTHING cursor on: 'h'
{
//if the input is "house" before entering EOF
putchar(c); //output: 'h' cursor on: 'o'
getchar(); //output: 'h' cursor on: 'u'
printf("%c", BACKSPACE); //output: 'h' cursor on: 'o'
getchar(); //output: 'h' cursor on: 'u'
printf("%c", BACKSPACE); //output: 'h' cursor on: 'o'
getchar(); //output: 'h' cursor on: 'u'
printf("%c", BACKSPACE); //output: 'h' cursor on: 'o'
}
} //ACTUAL END OUTPUT: "h"
I know regular backspacing in most programs looks like: printf("%c %c", 8 ,8); ..meaning backspace pretty much just moves the cursor back without deleting anything, just like how getchar() just moves the cursor forward.
I'm trying to understand why the sample code above's output isn't exactly the same as:
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF) //output: WE HAVE NOTHING cursor on: 'h'
{
//if the input is "house" before entering EOF
putchar(c); //output: 'h' cursor on: 'o'
}
} //ACTUAL END OUTPUT: "house"
EDIT: follow up question! How do I "reverse" a getchar() call?
#include <stdio.h>
main()
{
int c;
char a;
while((c = getchar()) != EOF)
{
a = c;
putchar(c);
a = getchar();
??????????
}
}
what do I have to put on "??????????", so that when I call getchar again to assign to c, it gets the char after the preceding assignment to c, and not the char after a.
Upvotes: 0
Views: 556
Reputation: 59184
Your output doesn't actually go to the same place that your input comes from.
The terminal collects your keystrokes. As you type it displays them and remembers them. When you hit ENTER it sends the keystrokes that it remembered to your program.
At the same time, it displays the output from your program. You may be able to get the terminal to erase the display of characters you typed, but that will not change its memory of the characters you typed and doesn't change the characters that get sent to your program.
to undo a single getchar(), you can use ungetc:
http://www.cplusplus.com/reference/cstdio/ungetc/
Upvotes: 2
Reputation: 54515
Your program is not actually reading from the terminal one character at a time. Instead, it is reading from a buffer which holds the entire line which you entered.
So:
h
, your program
h
,o
from the buffer, andh
)u
, and
s
, and
Some terminals will wrap the cursor back to the end of the previous line, and some will stop on the margin.
Upvotes: 2