How to read user input with the addition of space or some other character?

I want to read user input, something like this:

char *text  = new char[20] ;
cin >> text ;

but if the user enters hello, I want my other empty characters to be filled with a space or -something like:

"hello------------------------"

How can i do this?

+5
source share
3 answers

There is no standard and quick way to do this. I can come up with some options.


Let's pretend that:

char *text  = new char[20];
cin >> text;

Note. We needknow that the capacity is 20! I would recommend that you use some constant for this, especially if it will be used for other lines as well.


Ok, 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 it is rather slow.


Fill in the characters manually:

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

, , char* ( ) std::string.

std::string sText;
std::cin >> sText;
sText.resize( 20, '-' ); // NOTE - no need to NULL-terminate anything

Voilà! (:

, delete[] text; ( , - delete[]), 100% . , .. ?!:))


, 19 20-1, "" -1, .

+6

- '\ 0'. C/++. , , 20 , 21 . . :

char *text = new char[21];
//start initialization
for (int i=0;i<20;i++) {
    text[i] = '-';
}
text[20] = '\0';
//end initialization
cout << "Your input: " << endl;
cin >> text;//get the user input
text[strlen(text)]='-';//change the automatically added '\0' with '-'
cout << text << endl;

, , - , .


EDIT: , Kiril (), .:)

+2

. , , , 19 "-": ( , 20, 19 \0:

const char* dashes = "--------------------";

:

char *text  = new char[20] ;
cin >> text ;

and then you can use strcatto copy the rest of the characters, using strlento determine the length of the line read:

strcat(text, dashes + strlen(text));

This will add resting 19 - length of the textto the text. Please note that I am adding this amount to the pointer dashes.

Finally, >>only one word will be read. To read the full line of input, you should use getline.

0
source

All Articles