Standard template String class: string.fill ()

I need a way to create a string of n characters. In this case, the value of ascii is zero.

I know I can do this by calling the constructor:

string sTemp (125000, 'a');

but I would like to reuse sTemp in many places and fill it with different lengths.

I call a library that takes a string pointer and length as an argument and fills the string with bytes. (I know that technically the line does not touch, but for all purposes and tasks it is and will soon become the standard). I do NOT want to use a vector.

Is there any smart way to call the constructor again after creating the string?

+6
c ++ string
source share
2 answers

The string class provides an assign method to assign a new value to a given string. Captions

 1. string& assign ( const string& str ); 2. string& assign ( const string& str, size_t pos, size_t n ); 3. string& assign ( const char* s, size_t n ); 4. string& assign ( const char* s ); 5. string& assign ( size_t n, char c ); 6. template <class InputIterator> string& assign ( InputIterator first, InputIterator last ); 

Citation source: cplusplus.com (I recommend this site because it gives you a very detailed link to the standard C ++ libraries).

I think that you are looking for something like the fifth of these functions: n indicates the desired length of your string and c character filled in this string. For example, if you write

 sTemp.assign(10, 'b'); 

your line will be filled only 10 b.

Initially, I suggested using the std::fill STL algorithm, but at the same time, the length of your string remains unchanged. The string::resize method provides a way to resize a string and fills the added characters with the specified value - but only the added ones are set. Finally string::assign remains the best approach!

+12
source share

Try using:

 sTemp.resize(newLength, 'a'); 

Literature:

 void __CLR_OR_THIS_CALL resize(size_type _Newsize) { // determine new length, padding with null elements as needed resize(_Newsize, _Elem()); } void __CLR_OR_THIS_CALL resize(size_type _Newsize, _Elem _Ch) { // determine new length, padding with _Ch elements as needed if (_Newsize <= _Mysize) erase(_Newsize); else append(_Newsize - _Mysize, _Ch); } 
+3
source share

All Articles