You must always store 300 characters in string .

As I understand it, memory is allocated dynamically when assigned to an example:

 string ex = "Example"; 

I need to explicitly assign each character a value,

  ex.at(100) = '2'; 

but when executing the code there will be an error, because memory was not allocated, is it possible to specify the size of a string explicitly, as in a character array?

This option is not very

 for(int i=0;i<300;i++) ex += " "; 

    2 answers 2

    std::string in this regard has almost the same external interface specification as std::vector .

    Tell her

     ex.resize(300); 

    and you will be a string of size 300 . This version complements the string (if necessary) to a size of 300 null characters. And option

     ex.resize(300, 'a'); 

    accordingly, complement the characters 'a' .

    What is missing is the constructor corresponding to the first version of resize , i.e. when constructing a filler character, you will always have to explicitly specify

     std::string ex(300, 'a'); 

      Try this:

       string s(300, ' '); 

      Check: http://ideone.com/8Hqa7f

      • By the way, I tested, some code on the ideone service and this is just disgusting ... just stupidly does not catch errors, although they exist! So ideone is better not to use - MaximPro
      • @MaximPro: Of course. Services that do not provide access to the compiler settings should not be seriously considered. - AnT
      • 2
        @AnT: "seriously" it makes sense to consider the code only on your hardware, with software available to you. For everyone else, ideone demonstrates that the code produces the expected output (at least for some combination of hardware + software). What is definitely better than the absence of this information. - jfs
      • @MaximPro: can you give an example? - jfs
      • ideone in C mode silently passes int *p = 42; Try char *c = 0; int *p = c; char *c = 0; int *p = c; - silence again. To achieve this, it is necessary to deliberately "push" diagnostic messages, because in the GCC's demanding settings there will be at least a "warning" in response to such errors. - AnT