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:
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::stringstreamBut this is rather slow.
Fill the chars by hand:
And the best way, according to me – get rid of these
char*things (you have tagged the question as c++ ) and just usestd::string.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 beforedelete[]– 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
19instead of20-1, I just wanted to “highlight” the-1, in case that you use some constant.