I would like to read input char by char and save it as a word into char* array. I don't know how long the input will be, so i want to alloc the memmory dynamicaly. The program ends,when the char is whitespace. How can i do this using realloc? There is my code:
#include <stdio.h>
int main(void) {
char *word=malloc(1*sizeof(char));
char c;
int numOfChars=0;
c=getchar();
word[0]=c;
numOfChars++;
while((c=getchar())!=' '){
numOfChars++;
realloc(word,numOfChars);
word[numofChars-1]=c;
}
printf("%s", word);
return 0;
}
Example input:Word
Example output:Word
The program can look the following way. Take into account that the input is buffered and filled until a new line character is entered that is also a white space character. And the result word must be zero terminated if you are going to use format specifier %s
to output it.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int c;
size_t n;
char *word;
char *tmp;
n = 0;
word = malloc( n + 1 );
word[n++] = '\0';
printf( "Enter a word: " );
while ( ( c = getchar() ) != EOF && !isspace( c ) && ( tmp = realloc( word, n + 1 ) ) != NULL )
{
word = tmp;
word[n-1] = c;
word[n++] = '\0';
}
printf( "You've entered \"%s\"\n", word );
free( word );
}
The program output might look like
Enter a word: Hello
You've entered "Hello"