String input problems
Posted: Wed Aug 20, 2008 6:15 pm
I have an annoying problem, that I probably know the answer to, but it might be my sleep-lesss angry tired nees that makes it so that I can't figure it out.
Here is the code:
This is a simple thing to fill a buffer with keyboard input. It should print the character 'Q' as you typed (you type 'c', and 'cQ' should be displayed)
However, when you type 'hello', only that is displayed, as if the putchar() isn't even in there! When you press enter, then it prints out 'QQQQQ5'. And the string isn't printed, though it should be.
This has been annoying me for a while, can someone help?
-JL
Here is the code:
Code: Select all
#include <stdio.h>
int main()
{
char buf[256];
char str[1];
int i;
char c;
buf[0] = '\0';
i = 0;
while (1) {
c = getchar();putchar('Q');
if (c == '\r' || c == '\n') {
break;
}
if (c == '\b' || c == 0x7f) {
if (i > 0) {
i--;
buf[i] = '\0';
}
continue;
}
buf[i] = c;
str[0] = buf[i];
str[1]=0;
i++;
}
buf[i] = '\0';
printf("%d\n%s\n", i, buf);
return 0;
}
However, when you type 'hello', only that is displayed, as if the putchar() isn't even in there! When you press enter, then it prints out 'QQQQQ5'. And the string isn't printed, though it should be.
This has been annoying me for a while, can someone help?
-JL