If a string's length is determined at compile-time, how can I properly initialize it?
#include <string> int length = 3; string word[length]; //invalid syntax, but doing `string word = " "` will work word[0] = 'a'; word[1] = 'b'; word[2] = 'c';
...so that i can do something like this?
Example: http://ideone.com/FlniGm
My purpose for doing this is because I have a loop to copy characters from certain areas of another string into a new string.
The idea is to first, get the length L of the string is taken as input and then input the specific character C and initialize empty string str. Now, iterate a loop for L number of times. In every iteration, the specific character is concatenated with string str until the for loop ends.
std::string::resize() in C++ Syntax 1: Resize the number of characters of *this to num. void string ::resize (size_type num) num: New string length, expressed in number of characters.
A string is mutable and it's length can changed at run-time. But you can use the "fill constructor" if you must have a specified length: http://www.cplusplus.com/reference/string/string/string/
std::string s6 (10, 'x');
s6
now equals "xxxxxxxxxx".
How about the following?
string word; word.resize(3); word[0] = 'a'; word[1] = 'b'; word[2] = 'c';
More on resizing a string: http://www.cplusplus.com/reference/string/string/resize/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With