loops and cin

I thought I was smart trying to build my own string function, but it's way more complicated than I thought.

First problem, detecting whitespace:
1
2
3
4
5
6
7
	char wd[4];

	for(int i = 0; i < 4; i++)
	{
		cin >> wd[i];
		cout << i << ' ' << wd[i] << '\n';
	}

The above does not work as I intended which was to 1)cin one character 2)display it. What it does is takes 4 typed letters, then displays all 4 letters below what you typed one line for each letter:
1
2
3
4
5
word
w
o
r
d


Why does this happen?
Because your input is line-buffered. The OS doesn't let the program see the letters until Enter is pressed.

The way to turn it off is OS-specific, On Linux and similar systems, you'd use tcsetattr(), see for example the tty_raw() function here: http://www.cs.uleth.ca/~holzmann/C/system/ttyraw.c

Not sure how this is done in other OSes, but usually if you need this kind of I/O control, you switch to a console I/O library, such as curses (or use the WinAPI console I/O functions, if that's your OS)
Last edited on
Thanks, Cubbi.
Topic archived. No new replies allowed.