Hi -
1. There are several problems with your original code. First, here's sample output from the code you originally posted (it happens to "work", despite the two "strlen()" errors):
Code:
$ g++ -o x -Wall -pedantic test.c
$ ./test
9876543210
9876
2. The first problem is "memset(str,'\0',strlen(str));"
As you already saw, "str" isn't terminated, so strlen() is a bug.
One workaround is "memset (str, 0, sizeof(str));".
Perhaps a better solution might be to add the terminator after you've added all the characters.
3. The second problem is the "fflush()". You don't need it.
4. You're trying to read a character at a time. Fine.
But the OS gives you a LINE at a time.
In other words, you don't get ANY characters from the keyboard to your program until you hit <Enter>. Then you get them all at once.
This is the whole point behind "buffered input".
If you don't want this behavior (if you actually DO need to read a character at a time), then you need to look at a library like curses (which does text-mode screen control), or SDL (which lets you read individual events from a mouse, keyboard or joystick).
Here's a modified version of your code, and the corresponding output:
Code:
#include <stdio.h>
#include <string.h>
#define MAXCHAR 4
int
main (int argc, char *argv[])
{
char str[MAXCHAR+1];
int i=0;
for (i=0; i<MAXCHAR; i++)
{
scanf ("%c", &str[i]);
}
str[MAXCHAR] = '\0';
printf ("\n%s\n", str);
return 0;
}
Code:
$ g++ -o x -Wall -pedantic test.c
$ ./test
9876543210
9876