Well my other thread regarding the best way to get user input got me thinking. Using fgets() and fgetc() are great if you have an array of a predetermined size and you don't want to overflow the buffer.
It led me to a different question of how to handle user input of any size without limitation. I came up with the following code which sort of works except for some reason that I can't figure out it also seems to place garbage characters into the buffer along with the wanted ones.
When I enter the string: asdf
It gives me this as output, you can clearly see the 'a', 's', 'd', 'f' in there along with the garbage: aÍÍýýýýsÌÌÌÀ dÌÌÌÀ fÌÌÌÀÿ
Here is my code for anyone that wants to try and figure out my error:Code:#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char c1[1]; //used for fgetc char *ptr; //pointer to dynamic array int ar_size = 1; //incremental counter for size of dynamic array printf("\n- Enter a string: "); c1[0] = fgetc(stdin); ptr = (char *)calloc(ar_size, sizeof(char)); strcpy(ptr, c1); /* loop until no more chars in the input stream */ while( (c1[0] = fgetc(stdin)) != '\n' ) { ptr = (char *)realloc((char *)ptr, ar_size*sizeof(char)); strcat(ptr, c1); ar_size++; } printf("\n- Successfully allocated memory for: %s", ptr); /* used in Windows environment to keep window open */ printf("\n\nPress ENTER to exit..."); fgetc(stdin); return(0); }



LinkBack URL
About LinkBacks



