I want to read user input, something like here :
char *text = new char[20] ;
cin >> text ;
but if the user enters "hello", I want my other empty characters to be filled with space or -
, something like:
"hello------------------------"
How can I do this?
There's no standard and fast way to do this. I can think of some options.
Suppose we have:
char *text = new char[20];
cin >> text;
Note - we need to know that the capacity is 20! I'd recommend you to use some constant for this, especially if this will be used for other strings, too.
Okay, first option - use std::stringstream
std::stringstream ss;
ss << setw( 20 - 1 ) << setfill( '-' ) << text;
// ^^^^ we need one byte for the '\0' char at the end
ss >> text;
But this is rather slow.
Fill the chars by hand:
int length = strlen( text );
for( int i = length; i < 20 - 1; ++i ) // again - "20-1" - '\0'
{
text[ i ] = '-';
}
text[ 20 - 1 ] = '\0'; // don't forget to NULL-terminate the string
And the best way, according to me - get rid of these char*
things (you have tagged the question as c++ ) and just use std::string
.
std::string sText;
std::cin >> sText;
sText.resize( 20, '-' ); // NOTE - no need to NULL-terminate anything
Voilà! (:
This way is much more clear and you don't need to carry about using delete[] text;
at the end (which is not that trivial sometimes, especially in case of some exception before delete[]
- this will give you 100% memory leak. Of course, you can always use smart pointers.. but smart pointers for this?! :) )
Of course, you can write 19
instead of 20-1
, I just wanted to "highlight" the -1
, in case that you use some constant.
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