Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read user input with adding space or some other character?

Tags:

c++

string

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?

like image 817
Ata Avatar asked Jun 12 '11 09:06

Ata


1 Answers

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.

like image 155
Kiril Kirov Avatar answered Sep 28 '22 06:09

Kiril Kirov