Reputation: 21
int a=sizeof(out);
int b=sizeof(s2);
out+=s2;
out.insert(a,(70-a-b)," ");
out and s2 are strings. I want to add some space characters between the two strings and make the total length 70. VS wants "const char *" for the second parameter. I've read C++: insert char to a string but I still don't know how to modify my code given above.
Thanks for advice!
Upvotes: 0
Views: 234
Reputation: 2509
Refer to the documentation here.
Just correct the last instruction by this:
out.insert(a," ",(70-a-b<70)?(70-a-b):70);
Upvotes: 0
Reputation: 153909
While it shouldn't be too difficult to insert the text in
question, once you've gotten the correct size (using a.size()
and b.size()
), I question whether this is the best solution.
I'd probably append the necessary padding to out
before
appending s2
. Something like:
int padding = 70 - (asInt( out.size() ) + asInt( s2.size() ) );
if ( padding > 0 ) {
out.append( padding, ' ' );
}
out.append( s2 );
The extra tests are necessary because std::string
uses an
unsigned type (size_t
) for the size, and unsigned types in C++
tend to lead to some surprizing results. (The asInt
may or
may not be necessary, depending on where the strings come from.
They're basically:
int
asInt( size_t original )
{
if ( original > std::numeric_limits<int>::max() ) {
throw std::range_error( "size too large for int" );
return static_cast<int>( original );
}
In many cases, you will know that the strings cannot be too long before you get to this point in the code, and so you don't need them.
Note that you must convert the sizes to int
(or some other
signed type) before calculating the padding. Otherwise, the
calculation will give the wrong results.
Upvotes: 1
Reputation: 132994
out and s2 are strings. I want to add some space characters between the two strings and make the total length 70.
First of all, sizeof is the wrong operator here. You need
int a = out.size();
int b = s2.size() ;
One option to do what you want is
int spaceCount = 70-a-b;
out += string(spaceCount, ' ') + s2;
Another option is to use setw:
ostringstream resultSS;
resultSS << out << setw(70-out.size()) << right << s2;
out = resultSS.str();
Upvotes: 4