Reputation: 103
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])
Upvotes: 4
Views: 13149
Reputation: 206567
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.
Upvotes: 1