Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limiting string size in c++ to number of characters

Tags:

c++

i have gotten a good exposure in C but am new to C++. I was wondering, is there a way to limit C++ string to number of characters. For eg: if i want to declare a string named "circle", can i limit number of characters to 50? (like we used to do in C, char circle[50])

like image 996
Shrey Avatar asked Nov 21 '25 07:11

Shrey


1 Answers

can i limit number of characters to 50?

You can construct a string with the capacity to hold 50 characters by using:

std::string str(50, '\0');

However, unlike C arrays, it is possible to increase its size by adding more data to it.

Example:

#include <iostream>
#include <string>

int main()
{
   std::string str(50, '\0');
   for (size_t i = 0; i < 49; ++i )
   {
      str[i] = 'A'+i;
   }

   std::cout << str << std::endl;

   str += " Some more characters.";

   std::cout << str << std::endl;
}

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopq
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopq Some more characters.
like image 199
R Sahu Avatar answered Nov 22 '25 21:11

R Sahu