c++ - Why does getchar work like a buffer instead of working as expected in real-time -
this first question on stackoverflow. pardon me if haven't searched not seem find explanation this. attempting example bjourne stroustroup's papers. added bits see array re-sized type text.
but doesn't seem work way! getchar() waits till done entering characters , execute loop. per logic, doesn't go loop, character, perform actions , iterate. wondering if implementation specific, or intended this?
i on ubuntu 14.04 lts using codeblocks gcc 4.8.2. source in cpp files if matters.
while(true) { int c = getchar(); if(c=='\n' || c==eof) { text[i] = 0; break; } text[i] = c; if(i == maxsize-1) { maxsize = maxsize+maxsize; text = (char*)realloc(text,maxsize); if(text == 0) exit(1); cout << "\n increasing array size " << maxsize << endl; } i++; }
the output follows:
array size now: 10 please enter text: sample text. have liked see memory being realloced right here, apparently that's not how works!
increasing array size 20
increasing array size 40
increasing array size 80
increasing array size 160
you have entered: sample text. have liked see memory being realloced right here, apparently that's not how works!
array size now: 160
this has nothing getchar
directly. "problem" underlying terminal, buffer input. input sent program after press enter. in linux (dunno if there way in windows) can workaround calling
/bin/stty raw
in terminal or calling
system ("/bin/stty raw");
in program. cause getchar return input character you.
dont forget reset tty
behaviour calling
/bin/stty cooked
when done!
here example (for linux):
#include <stdio.h> #include <stdlib.h> using namespace std; int main() { system ("/bin/stty raw"); char c = getchar(); system ("/bin/stty cooked"); return 0; }
also have @ post: how avoid press enter getchar()
also, suggested in comments, have here: http://linux.die.net/man/3/termios on command tcsetattr
, should work cross-platform.
Comments
Post a Comment