EvilZone
Programming and Scripting => C - C++ => : Code.Illusionist May 27, 2013, 12:27:55 PM
-
I was wondering, because C have some retarded string manipulation, how to get string from user and store in array?
-
You can do either using predefined MAX_SIZE:
char string[MAX_SIZE];
printf("Enter a string: ");
fscanf(string, MAX_SIZE, stdin);
// fscanf also gets the newline character so we do this:
int length = strlen(string);
if (string[length-1] == '\n')
string[length-1] = '\0';
else {
printf("You entered a string that was too large to fit in the buffer!\n");
// clearing the rest of the char that are left from the user input
while (getchar() != '\n');
}
or you can allocate space dynamically. Do you want me to show you how? Cause this is mostly fine for most programs.
EDIT:
Almost forgot about clearing the buffer if the whole of user input was not stored.
-
Show me the other way as well.
-
Show me the other way as well.
I think you might want to look into the C programming basics instead of asking separate questions you would have learned otherwise.
-
I think this should work. It's not the most optimal way because of constant reallocs and possible wasted space, but it works and is dynamic. Don't forget to check the return value of fgets() for errors.
const unsigned int CHUNK_SIZE = 16; // whatever you want here
char *string = NULL;
int length = 0;
bool done = false;
while (!done) {
printf("Enter a string: ");
if (realloc(string, length+CHUNK_SIZE))
fscanf(string[length], CHUNK_SIZE, stdin);
else {
fprintf(stderr, "Out of memory!\n");
break;
}
length += strlen(string[length]);
if (string[length-1] == '\n') {
string[length-1] = '\0';
done = true;
}
}
-
Thank you s3my0n. :)