for loop problem

Hi all,

I am new for this forum. I have a question about a for loop in c language(sorry it is not a c++ question): I try to get 5 characters one by one from the keyboard and print them out. The for loop repeats 5 times BUT only accept 3 characters from keyboard. I wonder if anyone there can explains why.

Thanks,

Li

#include <stdio.h>

main()
{
int i;
int ch;

for( i = 1; i<= 5; i++ ) {
printf("%d\n",i);
ch= getchar();
putchar(ch);
}
}



output:

1
a
a2

3
b
b4

5
c
c
It is because the console input is line buffered. The second and fourth characters are the newline character (\n). Try responding with all five characters when it asks for 1.

Hope this helps.
Hi Duoas,

Thank you.

When I feed the program five letters(a, b,c,d,e) all at once as 'abcde' followed by 'Enter' key the program runs and prints out all letters one by one. But this behavior is different from what I originally want: I want to do it interactively: enter one letter then print out one letter, and so on. How do I modify the codes to achieve this goal?

Li
Alas, you are in for a world of hurt. Are you sure your program must do it interactively?

If undaunted, I recommend you to the NCurses library.

NCurses
POSIX (Unix, Linux, etc)
http://www.gnu.org/software/ncurses/

PDCurses
DOS, OS/2, Win32, etc
http://pdcurses.sourceforge.net/

Check out the Wikipedia page for good links to get started
http://en.wikipedia.org/wiki/Ncurses#External_links

Here's a simple example (in C++):
http://www.cplusplus.com/forum/lounge/2489/page1.html#msg9631

Good luck!
Instead of using "getchar( )" use " getch( ) "... now the pgm works as what you originally want.

Difference between getchar() and getch()

getchar() : It gets the character from the keyboard and waits while the user hit the "Enter Key" before reading the character.

getch() : It reads any character without hitting the Enter key...

The modified code :
------------------------

void main()
{
int i;
int ch;

for( i = 1; i<= 5; i++ )
{
printf("%d\n",i);
ch= getch(); // Use getch() instead of using getchar()
putchar(ch);
}
}

Thanks,
RK
The getch() function is non-standard, and probably only works as you have it because you are using an old Borland or MS compiler, which let you use it without properly #including <conio.h>.

If you use the curses library, as I suggest, then you will have standardized, cross-platform code that allows you to do what you want.


Use getchar() function to get the character and after that use " fflush(stdin) " to flush the standard input...

Modified code :
-------------------

void main()
{
int i;
int ch;

for( i = 1; i<= 5; i++ )
{
printf("\nKarthik\n");
printf("\n%d\n",i);
ch=getchar(); // getchar() .
fflush(stdin); // Added Newly.
putchar(ch);
}
}

Thanks,
RK
Topic archived. No new replies allowed.