Reading in a string of unknown length from the console

If I want to read a string from an arbitrary length from the command line, what is the best way to do this?

I am currently doing this:

char name_buffer [ 80 ]; int chars_read = 0; while ( ( chars_read < 80 ) && ( !feof( stdin ) ) ) { name_buffer [ chars_read ] = fgetc ( stdin ); chars_read++; } 

But what should I do if the string is longer than 80 characters? Obviously, I could just initialize the array with a large number, but I'm sure there should be a better way to give the array more space using malloc or something else?

Any tips would be great.

+4
source share
2 answers

Found it somewhere on the network for a long time, its really useful:

 #include <stdio.h> #include <stdlib.h> int main() { unsigned int len_max = 128; unsigned int current_size = 0; char *pStr = malloc(len_max); current_size = len_max; printf("\nEnter a very very very long String value:"); if(pStr != NULL) { int c = EOF; unsigned int i =0; //accept user input until hit enter or end of file while (( c = getchar() ) != '\n' && c != EOF) { pStr[i++]=(char)c; //if i reached maximize size then realloc size if(i == current_size) { current_size = i+len_max; pStr = realloc(pStr, current_size); } } pStr[i] = '\0'; printf("\nLong String value:%s \n\n",pStr); //free it free(pStr); pStr = NULL; } return 0; } 
+13
source

Use realloc() to allocate a buffer and expand it when it is full.

+2
source

Source: https://habr.com/ru/post/1344573/


All Articles