I want to create a string of any size, that is, not to create a constant, in often:

const int max_size_str = 256; 

But count the number of characters from the input buffer entered before '\ n' + 1 (for \ 0) and write as the size of the line so that you can specify the size of the line by the number of characters entered.


I am aware of how to use dynamic memory. I give an example of my question, I do not specify the size of the array of characters, I write a string from the keyboard, after which the number of characters in this string is considered and a dynamic array of characters is created, and then from the input buffer, what I wrote there (the string) is copied into the created array is then added with a 0 at the end to read as a string.

  • In the context of C ++, this question does not make sense. The lines in the pluses do not have a fixed size by design. Or are you talking about something else? - PinkTux
  • Well, dynamically allocate memory for the array. int i = 0; cin << i; char str = new char [i]; prog-cpp.ru/cpp-newdelete - Evgeny Ivanov
  • one
    When creating a string, whether it is a dynamic or static array, we set the size, and then we only enter characters into this array, then we put instead of '\ n' '\ 0' functions like gets_s (string, size), and I want First, write a line, read its size and create an array of characters of this size, because if we have an array initially of only 256 elements, and the user enters 257, everything flies - BlackKnight
  • one
    @BlackKnight, std::getline(std::cin, s); - eanmos
  • one
    I did not know that the string so can XD. I may seem like a fool, but please give an example on pure C, that is, using an array of characters with 0, and not with a string class that is ultra cool and already can do everything) - BlackKnight

2 answers 2

Here's a sketch for C, since you need it so much ...

 int main(int argc, const char * argv[]) { char * s = malloc(1); int size = 1; char c; while((c = getc(stdin))!='\n') { s = realloc(s,size+1); s[size-1] = c; size++; } s[size-1] = 0; printf("[%s]\n",s); } 

But! written on the knee, without checking for errors of the same realloc , is extremely inefficient (constant memory allocation is one character at a time; more correctly, a buffer that grows, say, 2 times).

So, no more than to demonstrate the idea.

  • In principle, almost the same :-) - PinkTux
  • as an option: pcdev.ru/read-line-from-stdin - Croessmah
  • Thanks, I will understand). And by the way, I use instead of 'malloc' 'new', I think it should not strongly influence the functional - BlackKnight
  • @BlackKnight, still it would be good to decide: C or C ++. These are different languages. The fact that new is used instead of malloc does not mean anything. - PinkTux
  vector<char> v; copy(istream_iterator<char>(cin), istream_iterator<char>(), back_inserter(v)); // у вас уже есть вектор с таким размером...