What's the best way to truncate user input to a certain number of characters ( ie.6 characters)? tried using the following code but it doesn't seem to work properly for certain inputs.
If I input only a newline the output is:
�@
If I input ctrl +D the output is:
�@
If I input one character, for example 'a' the output is:
a@
If I input two characters, for example 'ab' the output is:
ab@
For three or more characters the output appears to be correct and if I enter more characters than MAX, the output appears to be properly truncated.
Can someone point out what I'm doing wrong?
Code:#include <stdio.h> #define MAX 6 int main(void) { int c; char array [MAX]; int count = 0; while((c = getchar()) != EOF && count < MAX && c != '\n') { array[count++] = c; } printf("\n%s", array); printf("\n"); return 0; }



LinkBack URL
About LinkBacks




